tjugg
tjugg

Reputation: 3357

Using a backing field with One-To-Many relationships

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

Upvotes: 3

Views: 1982

Answers (1)

Bartho Bernsmann
Bartho Bernsmann

Reputation: 2503

I was just facing the same problem earlier. This is how I was able to setup a private backing field for my List.

public class Entity
{
    private readonly List<User> _invitedUsers = new List<User>()

    public IReadOnlyCollection<User> InvitedUsers => _invitedUsers;

    public void AddInvitedUser(User user)
    {
        invitedUsers.Add(user);
    }
}

And this is how I've setup my DbContext:

var navigation = modelBuilder.Entity<Entity>().
    .HasMany(d => d.InvitedUsers)
                .WithOne(p => p.Entity) // notice that in your case this might be empty.. simply .WithOne()
                .HasForeignKey(d => d.EntityId)
      .Metadata.DependentToPrincipal.SetPropertyAccessMode(PropertyAccessMode.Field);

Upvotes: 1

Related Questions