I have combined 3 of my tables by using linq join. After that i want to update this table by using data that i get from webform. How can i do this ? My implementation is below
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
};
}
Though your approach is a little bit unclear right now (for eg we don't know which entities you are trying to update), however you can modify your code like this,
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();
}
Rather picking selected properties from each Entity, you can pick whole entity. Then you can update each entity in a loop as I have doing above.
To update an entity you will need to retrieve the entity from the context, modify the values, then call SaveChanges() to do the update.
foreach( var n in query)
{
var shoe = db.Shoes.Find(n.ShoeID);
shoe.Size = webFormData.Size;
}
db.SaveChanges();
I like the all-in-one linq update. Especially if I need to join on an existing object list.
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
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.