I have 2 tables: Orders and Customers. Orders is related to Customers by the IdCustomer foreign key.
Problem: I want to show in the DataGrid the values from both tables and want to be able to edit the data belonging to the Orders table.
I managed to show and edit in the grid the Orders table, but how do I include the data from the Customers table?
this.grdData.ItemsSource = context.Orders;
private void btnSave_Click(object sender, RoutedEventArgs e)
{
context.SaveChanges();
}
Usually, if you have a fk in your table, you'll have a relationship in your entity. If you don't have it, you should add it.
The best approach is to create a ViewModel class for what you want to show from both entities:
public class OrderViewModel {
public string CustomerName{ get; set; }
public decimal OrderTotal { get; set; }
public DateTime Date { get; set; }
}
Then you need to execute a query that retrieves all the information:
var query = from o in dataContext.Orders
select new ViewModel {
CustomerName = o.Customer.Name,
OrderTotal = o.Total,
Date = o.Date
};
and use it as the data source for the Grid.
If by any chances you don't have the relationship in your model, you can do a less straight forward query:
var query = from o in dataContext.Orders
join c in dataContext.Customers on o.CustomerId equals c.Id
select new ViewModel {
CustomerName = c.Name,
OrderTotal = o.Total,
Date = o.Date
};
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.