How do I SaveChanges on a joined view of 2 or more tables using Entity Framework?

半腔热情 提交于 2019-12-06 09:47:16

EF is not seeing your changes because your data grid view is not bound to the EF entities, but rather an object populated from it's entities:

select new CustAndOrders
    {
        Cust_Id = c.CustId,
        Cust_Name = c.CustName,
        Cust_BDay = c.CustBday,
        Order_Id = o.OrderId,
        Order_Amt = o.OrderAmount,
        Order_Date = o.OrderDate,
        Item_Number = od.ItemNumber,
        Item_Amt = od.ItemAmount
    };

One solution I can think of is to compose CustAndOrders of the entities themselves:

public class CustAndOrders
{
    public Customer Customer { get; set; }
    public Order Order { get; set; }
    public OrderDetail OrderDetail { get; set; }
}

And then bind to those fields i.e.

{Binding Customer.CustId}

Or if you don't want to change your bindings then pass the EF entities into the CustAndOrders object and in your properties just get and set from the entities:

public class CustAndOrders
{
    public Customer Customer { get; set; }
    public Order Order { get; set; }
    public OrderDetail OrderDetail { get; set; }

    // Customer table
    public Int64 Cust_Id
    {
        get
        { return Customer.CustId;}
        set
        { Customer.CustId = value; }
    }
... Do this for the rest of your properties

And then query looks like this:

var query = from c in dc.Customers
                join o in dc.Orders on c.CustId equals o.CustId
                join od in dc.OrderDetails on o.OrderId equals od.OrderId
                orderby o.OrderDate ascending, c.CustId, o.OrderAmount
                select new CustAndOrders { Customer = c, Order = o, OrderDetail = od };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!