简体   繁体   English

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

[英]Entity Framework entity list always null

I have the following two models: 我有以下两种模型:

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;
    }
}

And: 和:

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;
    }
}

My problem is this: Whenever a new instance of User is created and persisted to the database via EF, when I later get the entity back from the DB, the List of Note s is always null . 我的问题是:每当创建新的User实例并通过EF持久化到数据库时,当我以后从数据库取回实体时, Note List始终为null

I've managed to track down the bug to the following method: 我设法将错误归结为以下方法:

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;
}

Inspecting user1 and user2 via the debugger reveals that user1 , which was created before the first context was disposed of, is an initialized List<Note> with 0 items, whereas user2 , which was created in a new context, is null. 通过调试器检查user1user2可以发现, 处理第一个上下文之前创建的user1是具有0个项目的初始化List<Note> ,而在新上下文中创建的user2为null。

在此处输入图片说明

My context is very simple: 我的情况很简单:

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; }
}

The DB provider is MySQL. 数据库提供程序是MySQL。 Inspecting the tables EF generates in MySQL Workbench reveals that the foreign key is indeed there: 检查EF在MySQL Workbench中生成的表可以发现外键确实存在:

在此处输入图片说明

Adding new instances of Note with their Creator property set equal to my user's Id yields the exact same result. 添加其Creator属性设置为等于我的用户IdNote实例将产生完全相同的结果。

Why is this happening? 为什么会这样呢?

Do you have lazy loading configured? 您是否配置了延迟加载

If not, you need to Include a related entity explicitly like below ( Eager loading ) 如果不是,则需要像下面这样明确地Include相关实体( 急切加载

Your first example works because those entities are already in the context 您的第一个示例有效,因为这些实体已经在上下文中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM