Entity Framework Many to many through containing object

前端 未结 1 2005
温柔的废话
温柔的废话 2020-11-30 02:08

I was curious if it is possible to map an intermediate table through a containing object.

public class Subscriber : IEntity
{
    [Key]
    public int Id { g         


        
相关标签:
1条回答
  • 2020-11-30 02:30

    You can map private properties in EF code-first. Here is a nice description how to do it. In your case it is about the mapping of Subscriber._subscribedList. What you can't do is this (in the context's override of OnModelCreating):

    modelBuilder.Entity<Subscriber>().HasMany(x => x._subscribedList);
    

    It won't compile, because _subscribedList is private.

    What you can do is create a nested mapping class in Subscriber:

    public class Subscriber : IEntity
    {
        ...
        private ICollection<HelpChannel> _subscribedList { get; set; } // ICollection!
    
        public class SubscriberMapper : EntityTypeConfiguration<Subscriber>
        {
            public SubscriberMapper()
            {
                HasMany(s => s._subscribedList);
            }
        }
    }
    

    and in OnModelCreating:

    modelBuilder.Configurations.Add(new Subscriber.SubscriberMapping());
    

    You may want to make _subscribedList protected virtual, to allow lazy loading. But it is even possible to do eager loading with Include:

    context.Subscribers.Include("_subscribedList");
    
    0 讨论(0)
提交回复
热议问题