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.
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:
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?


public List<Note> Notes { get; set; }usepublic virtual ICollection<Note> Notes { get; set; }