【问题标题】:How to view and edit data from multiple tables in a DataGrid with EF?如何使用 EF 查看和编辑 DataGrid 中多个表中的数据?
【发布时间】:2012-10-01 05:31:05
【问题描述】:

我有 2 个表:订单和客户。订单通过 IdCustomer 外键与客户相关。

问题:我想在 DataGrid 中显示两个表中的值,并希望能够编辑属于 Orders 表的数据。

我设法在网格中显示和编辑 Orders 表,但如何包含 Customers 表中的数据?

this.grdData.ItemsSource = context.Orders;

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    context.SaveChanges();
}

【问题讨论】:

    标签: c# .net wpf entity-framework


    【解决方案1】:

    通常,如果您的表中有一个 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
                                     };
    

    并将其用作 Grid 的数据源。

    如果你的模型中没有任何关系,你可以做一个不那么直接的查询:

    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
                                      };
    

    【讨论】:

    • 通过这种方法,我将数据从 A 复制到 B,在 B 中对其进行编辑,然后将其复制回 A。这是很多额外的工作。我不能编辑A中的数据吗?
    • 你的模型中的实体之间有关系吗?
    • 是的,我有关系。
    • 您是否尝试将网格绑定到您的订单并使用Customer.Name 作为列表达式?
    • 是的。有效。谢谢。我为网格设置了 AutoGenerateColumns="True",所以我认为我没有来自客户的数据,因为来自客户的列还没有出现。专门询问 Customer.Name 列有效:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多