2

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 Notes is always 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.

enter image description here

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. Inspecting the tables EF generates in MySQL Workbench reveals that the foreign key is indeed there:

enter image description here

Adding new instances of Note with their Creator property set equal to my user's Id yields the exact same result.

Why is this happening?

2
  • 1
    Instead of public List<Note> Notes { get; set; } use public virtual ICollection<Note> Notes { get; set; } Commented Aug 1, 2017 at 19:37
  • 1
    Entity Framework Loading Related Entities Commented Aug 1, 2017 at 19:43

1 Answer 1

5

Do you have lazy loading configured?

If not, you need to Include a related entity explicitly like below (Eager loading)

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;
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.