繁体   English   中英

Linq在加入过程后更新不同的表

[英]Linq updating different table after join process

我已经使用linq join合并了3个表。 之后,我想使用从Webform获取的数据来更新此表。 我怎样才能做到这一点 ? 我的实现如下

public void updateShoes(Shoe shoe) 
{
    var query = from b in db.BrandTbls.AsQueryable()
                join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
                join s in db.ShoeTbls on m.ModelID equals s.ModelID
                where shoe.ShoeID == s.ShoeID 
                orderby m.ModelName
                select new 
                { 
                    s.ShoeID,
                    s.Size,
                    s.PrimaryColor,
                    s.SecondaryColor,
                    s.Quantity,
                    m.ModelName,
                    m.Price,
                    b.BrandName
                };
}

尽管您的方法目前尚不清楚(例如,例如,我们不知道您要更新哪个实体),但是您可以像这样修改代码,

public void updateShoes(Shoe shoe) 
{
    var query = from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            where shoe.ShoeID == s.ShoeID 
            orderby m.ModelName
            select new 
            { 
                Shoe = shoe, Brand = b, Model = m
            };

    foreach(var o in query)
    {
        o.Shoe.ColorName = "Black";
        o.Brand.BrandName = "New Branding";
        o.Model.ModelName = "Something else";
    }

    db.SaveChanges();
}

您可以选择整个实体,而不是从每个实体中选择选定的属性。 然后,您可以像上面一样在循环中更新每个实体。

要更新实体,您需要从上下文中检索实体,修改值,然后调用SaveChanges()进行更新。

foreach( var n in query)
{
  var shoe = db.Shoes.Find(n.ShoeID);
  shoe.Size = webFormData.Size;
}
db.SaveChanges();

我喜欢多合一的linq更新。 尤其是当我需要加入现有对象列表时。

var UpdQuery = (from b in db.BrandTbls
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            where shoe.ShoeID == s.ShoeID 
            orderby m.ModelName
            select new { b, m, s }
            // now for the update portion of the query
            ).Select(result =>
            { 
                result.s.ShoeID = shoe.ID;
                result.s.Size = shoe.Size;
                result.s.PrimaryColor = shoe.PrimaryColor;
                result.s.SecondaryColor = shoe.SecondaryColor;
                result.s.Quantity = shoe.Quantity;
                result.m.ModelName = shoe.ModelName;
                result.m.Price = shoe.Price;
                result.b.BrandName = shoe.BrandName;
                return result; // this is important
            }).ToList();  // tolist actually runs the query to update the objects
db.SaveChanges(); // write changes back to DB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM