list.Clear()与新的List <>()-ASP.NET Core-实体框架Core-延迟加载

时间:2018-09-08 14:43:20

标签: .net asp.net-core entity-framework-core asp.net-core-2.1 entity-framework-core-2.1

经过一段时间的调查,为什么我的导航属性再次被我刚刚删除的实体填充(使用entity.NavigationPropertiesCollection = new List <>()),我意识到,使用entity.NavigationPropertiesCollection.Clear()一切正常。我的问题是,为什么在我重新初始化导航属性集合之后,Entity Framework Core会再次加载导航属性?为什么使用Entity.NavigationPropertiesCollection.Clear()一切正常? (按预期方式将其删除)

必备的nuget软件包: Microsoft.EntityFrameworkCore.Proxies

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

必备代码:

public class FooChildEntity
 {
       public int Id { get; set; }
       public string Name { get; set; }
 }
public class FooParentEntity
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual List<FooChildEntity> FooChildEntities { get; set; }
}

internal class FooDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer(@"Server=.\sqlexpress;Database=fooDb;Trusted_Connection=True;");
    }

    public DbSet<FooParentEntity> FooParentEntities { get; set; }
} 

要复制的代码:

首先运行此代码:

     FooParentEntity fooParentEntityInput = new FooParentEntity
        {
            Title = "cool title",
            FooChildEntities = new List<FooChildEntity>
            {
                new FooChildEntity
                {
                    Name = "FirstChild"
                },
                new FooChildEntity
                {
                    Name="SecondChild"
                }
            }
        };

        FooDbContext fooDbContext = new FooDbContext();
        fooDbContext.FooParentEntities.Add(fooParentEntityInput);

        fooDbContext.SaveChanges();

并删除它或将其注释掉。

之后,下面的代码使用了截屏中的断点

FooDbContext fooDbContext = new FooDbContext();

FooParentEntity fooParentEntityDb = fooDbContext.FooParentEntities.ToList().FirstOrDefault();
fooParentEntityDb.FooChildEntities = new List<FooChildEntity>();
fooParentEntityDb.FooChildEntities.Add(new FooChildEntity { Name = "ThirdChild" });
  

此处出现错误:https://i.stack.imgur.com/tZ1j0.png

     

但是,如果   在调试时使用多个断点,如屏幕截图所示:   https://i.stack.imgur.com/naCxJ.png   https://i.stack.imgur.com/Ky7K5.png   https://i.stack.imgur.com/iziRr.png

     

一切正常。

0 个答案:

没有答案