实体框架6-延迟加载需要空集合,但返回null(仅在测试中)



我使用带有延迟加载的EF6代码优先模型。我有一个普通的项目(ASP.NET MVC)和一个测试项目。我在init(之前删除exlists)中创建了一个用于测试的普通数据库(没有嘲讽)。我在两个项目中使用相同的初始值设定项(为了找到问题,我尝试使用相同的connectionString来创建上下文)。

当我使用属性witch is collection(来自其他表的数据)时,没有元素,只有在正常的项目ef send sql请求中(我使用sql Server Profiler进行检查),在测试项目中,此属性始终为null。如果集合不是空的,那么在这两种情况下都是正确的。

这是我的代码的简单版本(如果你还需要什么,请告诉我,我不知道哪里有错误):数据模型:

public class Story
{
   public int Id { get; set; }
   public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
   public int Id { get; set; }
   [Index("CommentClusteredIndex_StoryId", IsClustered = true)]
   public int StoryId { get; set; }
   public virtual Story Story { get; set; }
}

Web.config(项目),App.config(测试):

<configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
<connectionStrings>
    <add name="StoriesEntitiesTestContext" connectionString="Data Source=(localdb)v11.0;Initial Catalog=StoriesEntitiesTestDb;Integrated Security=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

这就是我在正常项目中使用它的方式-代码exlist(这个没有测试):

public void Method(DbContext context)
{
            DbSet<Story> _dbSet = context.Set<Story>();
            var a = dbSet.First().Comment; //when Comment doesn't have items a is null in testing project and empty collection in normal project
}

如果你想获得空集合而不是null,你必须将构造函数添加到带有集合的实体中,并在构造函数中初始化一个空集合。

public class Story
{
   public int Id { get; set; }
   public virtual ICollection<Comment> Comments { get; set; }
   public Story()
   {
       Comments = new List<Comment>();
   }
}

类似的东西。

您需要在构造函数中实例化集合:

public class Story
{
    public Story()
    {
        Comments = new Collection<Comments>();
    }
    public int Id { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

最新更新