我有 2 个表:订单和客户。订单通过 IdCustomer 外键与客户相关。
问题:我想在 DataGrid 中显示来自两个表的值,并希望能够编辑属于 Orders 表的数据。
我设法在网格中显示和编辑订单表,但如何包含客户表中的数据?
this.grdData.ItemsSource = context.Orders;
private void btnSave_Click(object sender, RoutedEventArgs e)
{
context.SaveChanges();
}
最佳答案
通常,如果您的表中有一个 fk,那么您的实体中就会有一个关系。如果没有,则应添加它。
最好的方法是为您希望从两个实体显示的内容创建一个 ViewModel 类:
public class OrderViewModel {
public string CustomerName{ get; set; }
public decimal OrderTotal { get; set; }
public DateTime Date { get; set; }
}
然后您需要执行一个检索所有信息的查询:
var query = from o in dataContext.Orders
select new ViewModel {
CustomerName = o.Customer.Name,
OrderTotal = o.Total,
Date = o.Date
};
并将其用作网格的数据源。
如果您有任何机会在您的模型中没有关系,您可以做一个不那么直接的查询:
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
};
关于c# - 如何使用 EF 查看和编辑 DataGrid 中多个表的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12667929/