I have a situation where I have entity, which should expose a list of Users, and I only wish to expose IEnumerable, not List. So I use a backing field to achieve this. Something like below:
public class Entity
{
private readonly List<User> invitedUsers = new List<User>()
public IEnumerable<User> InvitedUsers => invitedUsers;
public void AddInvitedUser(User user)
{
invitedUsers.Add(user);
}
}
Now somewhere in a repository, I do this:
var user = new User();
var items = context.Items;
items.First().AddInvitedUser(user);
context.SaveChanges();
And in my modelbuilder, I set the navigation property to use a backing field
var navigation = modelBuilder.Entity<Entity>().
Metadata.FindNavigation(nameof(Entity.InvitedUsers));
navigation.SetPropertyAccessMode(PropertyAccessMode.Field);
So as far as I understand, this is everything that I should do to make this work. However, every time I access the same Entity, it doesn't load the persisted Users, and it doesn't even create the Users column to the database (Migrations are done). What am I missing here? Thanks in advance