Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 614
tjugg Avatar asked Oct 15 '25 17:10

tjugg


1 Answers

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);
like image 142
Bartho Bernsmann Avatar answered Oct 18 '25 11:10

Bartho Bernsmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!