实体框架实体列表始终为null

时间:2017-08-01 19:33:05

标签: c# entity-framework

我有以下两种模式:

public class Note
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; private set; }

    [Required] public string Creator { get; set; }

    public NoteProfile Profile { get; set; }

    [Required(AllowEmptyStrings = true)]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Content { get; set; }

    public static Note Create()
    {
        return new Note();
    }

    public Note GenerateId()
    {
        this.Id = Guid.NewGuid().ToString();
        return this;
    }

    public Note Finalize()
    {
        this.GenerateId();
        this.Profile = NoteProfile.Create().Finalize();

        return this;
    }
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; private set; }

    [ForeignKey("Creator")]
    [Required]
    public List<Note> Notes { get; set; }

    public static User Create()
    {
        return new User();
    }

    public User GenerateId()
    {
        this.Id = Guid.NewGuid().ToString();
        return this;
    }

    public User Finalize()
    {
        this.GenerateId();
        if (this.Notes == null)
        {
            this.Notes = new List<Note>();
        }

        return this;
    }
}

我的问题是:每当创建User的新实例并通过EF持久化到数据库时,当我稍后从数据库返回实体时,Note的列表始终是null

我已设法通过以下方法追踪错误:

public static bool AddUser(Models.API.Requests.POST.User post)
{
    var entity = User.Create().Finalize();
        List<Note> user1;
        List<Note> user2;
        using (var context = new Context())
        {
            context.Users.Add(entity);
            context.SaveChanges();
            user1 = context.Users.First(user => user.Id == entity.Id).Notes;
        }

        using (var context = new Context())
        {
            user2 = context.Users.First(user => user.Id == entity.Id).Notes;
        }

        return true;

    return true;
}

通过调试器检查user1user2会发现{<1}}是在第一个上下文被处理之前创建的,是一个初始化的{{1}带有0个项目,而在新上下文中创建的user1为空。

enter image description here

我的上下文非常简单:

List<Note>

数据库提供程序是MySQL。检查EF Workbench中生成的EF表显示外键确实存在:

enter image description here

添加user2的{​​{1}}新实例,其public class Context : DbContext { public Context(string connectionString) : this(new MySqlConnection(connectionString), false) { } public Context(DbConnection existing, bool contextOwnsConfig) : base(existing, contextOwnsConfig) { } public DbSet<Note> Notes { get; set; } public DbSet<User> Users { get; set; } } 属性设置等于我的用户的Note会产生完全相同的结果。

为什么会这样?

1 个答案:

答案 0 :(得分:4)

您是否配置了lazy loading

如果没有,您需要Include显式明确相关实体(Eager loading

您的第一个示例有效,因为这些实体已经在上下文中

using (var context = new Context())
            {
                user2 = context
                        .Users
                        .Include(b => b.Notes) 
                        .First(user => user.Id == entity.Id)
                        .Notes;
            }