我有以下一对多关系的类(class)
public class Category
{
public Category()
{
this.Products = new List<Product>();
}
public int Id {get;set;}
public string Name {get;set;}
public ICollection<Product> Products {get;set;}
}
public class Product
{
public int Id {get;set;}
public string Name {get;set;}
public int CategoryId {get;set;}
public Category Category {get;set;}
}
My datacontext is as shown below:
public class MyContext : DbContext
{
public virtual IDbSet<Category> Categories { get; set; }
public virtual IDbSet<Product> Products { get; set; }
}
我想用一个新的类别集合替换一个类别的现有产品collectino。
在 EF 中执行此操作的最佳方法是什么?
基本上,从提供的集合中,如果指定了 productid,则进行更新,如果实体不可用,则添加新产品。
如果不在列表中,则从数据库中删除。
这就是我想要的。
using (var dbCtx = new MyDBEntities())
{
//1- Get data from database
//2- Find newly added items
//3- Find deleted items
//4- Find modified
//5- Mark all added items entity state to Added
//6- Mark all deleted item entity state to Deleted
//7- Apply modified items current property values to existing property values
dbCtx.SaveChanges();
}
最佳答案
让我们注意这些行:
您不认为您正在尝试编写非常相似的代码来定义每个实体的状态吗?
我们可以用一个命令处理所有这些操作。
您可以使用新发布的 EntityGraphOperations 轻松实现这一目标。对于 Entity Framework 代码优先。我是这个产品的作者。我已将其发表在 github , code-project和 nuget .在
InsertOrUpdateGraph
的帮助下方法,它会自动将您的实体设置为 Added
或 Modified
.并在 DeleteMissingEntities
的帮助下方法,您可以删除那些存在于数据库中但不在当前集合中的实体。// This will set the state of the main entity and all of it's navigational
// properties as `Added` or `Modified`.
context.InsertOrUpdateGraph(category)
.After(entity =>
{
// And this will delete missing products.
entity.HasCollection(p => p.Products)
.DeleteMissingEntities();
});
更新:
经过一些评论,我决定制作示例项目并解释如何编写示例项目。我已经更新 my article in Code-project带有分步演示和示例项目可供下载。
关于entity-framework - C# 在 EntityFramework 中删除多个集合的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894225/