I am using EntityFramework which creates a local database and I would like to perform Join operation to show the Purchases done for each Customer, but I can't see to make it work.
Here is my Customer Model
public class Customer
{
[Key]
public int custId { get; set; }
public string firstName { get; set; }
public string surname { get; set; }
public string addresss { get; set; }
}
Here is my Purchase Model
public class Purchase
{
public int purchaseId { get; set; }
public int custId { get; set; }
public int productId { get; set; }
public double price { get; set; }
public int quantity { get; set; }
public double deliveryFees { get; set; }
public double finalAmount { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime dateOfPurchase { get; set; }
}
I have tried to create a ViewModel which should keep each Model in the class, so that I could perform join and it is shown down below:
public class ViewModel
{
public Customer customer { get; set; }
public Purchase purchase { get; set; }
public List<Customer> customers;
public List<Purchase> purchases;
}
And I have created a Controller for ViewModel to try to
public ActionResult Index()
{
using (db)
{
var cust = (from p in db.PurchaseList
join c in db.Customers on p.custId equals c.custId
select new
{
id = p.custId,
firstName = c.firstName,
surname = c.surname,
total = p.finalAmount.ToString()
}
).ToList();
return View(cust);
}
}
The db variable is the context of the database that I am using.
public Context() : base("name=Context")
{
}
public void CreateDatabase()
{
}
public System.Data.Entity.DbSet<Models.Offer> Offers { get; set; }
public System.Data.Entity.DbSet<Models.Employee> Employees { get; set; }
public System.Data.Entity.DbSet<Models.Customer> Customers { get; set; }
public System.Data.Entity.DbSet<Models.User> Users { get; set; }
public System.Data.Entity.DbSet<Models.Purchase> PurchaseList { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
In my View page I am only doing a foreach to retrieve the data but it is always empty. Do you have any suggestion? Should I use a different approach to the above?
Have you given correct relationships in your dbContext class?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.