添加或删除dbSet和本地属性中的实体有何区别?

当我想删除一个属性时,我有两个选择:

  • myDbContext.MyType.Add(myEntity);
  • myDbContext.MyType.Local.Add(myEntity);

在这两种情况下,至少在我的情况下,看不出差异,但我不知道它是否有不同的行为。

是真的一样吗?

谢谢。

基于方法的文档:

myDbContext.MyType.Add(myEntity所);

  /// Begins tracking the given entity, and any other reachable entities that are /// not already being tracked, in the  state such that /// they will be inserted into the database when  is called. 

myDbContext.MyType.Local.Add(myEntity所);

  ///  /// Adds a new entity to the . If the entity is not being tracked or is currently /// marked as deleted, then it becomes tracked as . ///  ///  /// Note that only the given entity is tracked. Any related entities discoverable from /// the given entity are not automatically tracked. ///  

上面的第2段指定了两种方法之间的差异。

本质上,区别在于, DbSet.Add是递归的,它也会添加新的依赖实体。 Local.Add仅添加当前实体。

示例代码:

实体类型:

 public class Blog { public int Id { get; set; } public IList Posts { get; set; } } public class Post { public int Id { get; set; } } 

情况1:

 db.Blogs.Add( new Blog { Posts = new List { new Post(), new Post(), } } ); db.SaveChanges(); var query = db.Set().Count(); //Output will be 2 

案例2

 db.Blogs.Local.Add( new Blog { Posts = new List { new Post(), new Post(), } } ); db.SaveChanges(); var query = db.Set().Count(); //Output will be 0 

myDbContext.MyType.Add(myEntity所);

它将做以下:

将给定实体添加到已Added状态的集合下的上下文中,以便在调用SaveChanges时将其插入到数据库中。

myDbContext.MyType.Local.Add(myEntity所);

它将执行以下操作:

获取一个System.Collections.ObjectModel.ObservableCollection 1`,它表示此集合中所有已添加,未更改和已修改实体的本地视图。 在上下文中添加或删除实体时,此本地视图将保持同步。

同样,添加到本地视图或从本地视图中删除的实体将自动添加到上下文中或从上下文中删除。

备注:

通过使用数据填充集合,此属性可用于数据绑定,例如,使用Load扩展方法,然后通过此属性绑定到本地数据。 对于WPF直接绑定到此属性。 对于Windows窗体,绑定到在此属性上调用ToBindingList的结果