根据以下情况,我想从父实体更新子实体。
我按照以下方法解决了这个问题。
那是真的吗?
public int SaveBasket(Addition addition)
{
var entity = ApplicationDbContext.Additions.Include(x => x.Basket).SingleOrDefault(x => x.AdditionId == addition.AdditionId);
//Remove Basket
if (entity.Basket.Count > 0)
{
foreach (var item in entity.Basket)
{
context.Entry(item).State = EntityState.Deleted;
}
ApplicationDbContext.SaveChanges();
}
//Add new basket entities from posting json data
entity.Basket = addition.Basket;
return ApplicationDbContext.SaveChanges();
}
答案 0 :(得分:0)
我认为您正在寻找以下内容:
public int SaveBasket(Addition addition)
{
var entity = ApplicationDbContext.Additions.Find(addition.AdditionId); // Find by primary key
//Remove Basket
if (entity.Basket.Count > 0)
{
entity.Basket.Clear(); // Empty out the basket
ApplicationDbContext.SaveChanges();
}
//Add new basket entities from posting json data
addition.Basket.ForEach(b => entity.Basket.Add(b)); // Add the items
return ApplicationDbContext.SaveChanges();
}
很难说出您的数据结构是什么,但这应该有所帮助。
更新
从您的评论看来,您似乎要删除整个basket
记录。
public int SaveBasket(Addition addition)
{
var baskets = ApplicationDbContext.Basket.Where(b => b.AdditionId == addition.AdditionId);
//Remove Basket
ApplicationDbContext.Basket.RemoveRange(baskets);
ApplicationDbContext.SaveChanges();
ApplicationDbContext.Basket.AddRange(addition.Basket);
return ApplicationDbContext.SaveChanges();
}
答案 1 :(得分:0)
根据模型的外观,您也许可以执行此操作以删除和添加子项。
public int SaveBasket(Addition addition)
{
var dbAddition = ApplicationDbContext.Additions
.Include(x => x.Basket)
.SingleOrDefault(x => x.AdditionId == addition.AdditionId);
ApplicationDbContext.Basket.RemoveRange(dbAddition.Basket);
ApplicationDbContext.Basket.AddRange(addition.Basket);
return ApplicationDbContext.SaveChanges();
}