从dbSet添加或删除实体与本地属性之间的区别如何? [英] How is the difference between add or delete an entity from the dbSet and from local property?

查看:113
本文介绍了从dbSet添加或删除实体与本地属性之间的区别如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我要删除某个属性时,我有两个选项:

When I want to delete a property, I have two options:


  • myDbContext.MyType.Add myEntity);

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

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

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

In both cases, at least in my case, don't see differences, but I don't know really if it has a different behavior or not.

真的是一样吗?

谢谢。

推荐答案

根据方法文档:


myDbContext.MyType.Add(myEntity );

myDbContext.MyType.Add(myEntity);



    ///     Begins tracking the given entity, and any other reachable entities that are
    ///     not already being tracked, in the <see cref="EntityState.Added" /> state such that
    ///     they will be inserted into the database when <see cref="SaveChanges()" /> is called.




myDbContext.MyType.Local.Add(myEntity);

myDbContext.MyType.Local.Add(myEntity);



    ///     <para>
    ///         Adds a new entity to the <see cref="DbContext" />. If the entity is not being tracked or is currently
    ///         marked as deleted, then it becomes tracked as <see cref="EntityState.Added" />.
    ///     </para>
    ///     <para>
    ///         Note that only the given entity is tracked. Any related entities discoverable from
    ///         the given entity are not automatically tracked.
    ///     </para>

上面的第2段指定了两种方法的区别。

The 2nd paragraph above specifies the difference between both the methods.

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

Essentially, the difference is, DbSet.Add is recursive, it will add new dependent entities too. Local.Add adds only current entity.

示例代码:

实体类型:

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

public class Post
{
    public int Id { get; set; }
}

案例1:

db.Blogs.Add(
    new Blog
    {
        Posts = new List<Post>
                {
                    new Post(),
                    new Post(),
                }
    }
);

db.SaveChanges();

var query = db.Set<Post>().Count(); //Output will be 2

案例2

db.Blogs.Local.Add(
    new Blog
    {
        Posts = new List<Post>
                {
                    new Post(),
                    new Post(),
                }
    }
);

db.SaveChanges();

var query = db.Set<Post>().Count(); //Output will be 0

这篇关于从dbSet添加或删除实体与本地属性之间的区别如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆