Entity Framework Many for many using an object

I was curious if it is possible to map the staging table through the containing object.

public class Subscriber : IEntity { [Key] public int Id { get; set; } public string Name { get; set; } private ChannelList _subscribedList { get; set; } public int NumSubscribedChannels { get { return _subscribedList.Count(); } } } public class HelpChannel : IEntity { [Key] public int Id { get; set; } public string name { get; set; } public string category { get; set; } public int group { get; set; } } 

I need to have a subscribers table, a channel table and an intermediate table in order to associate a subscriber with his / her channels.

Is it possible to map the list that is in the ChannelList object to the subscriber model?

I thought it was probably not possible and that I just need to have a private list for EF to display. But I was not sure that EF would do this for private variables. Will it be?

I hope so, because if it should be publicly available to support encapsulation.

+11
c # asp.net-mvc entity-framework
Dec 10 '12 at 19:01
source share
1 answer

You can map private properties in EF codes. Here is a good description of how to do this. In your case, it is about displaying Subscriber._subscribedList . What you cannot do is this (in the context of overriding OnModelCreating ):

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

It will not compile because _subscribedList is private.

What you can do is create a class of nested mappings 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 OnModelCreating :

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

You might want to make _subscribedList protected virtual to allow lazy loading. But you can even boot from Include :

 context.Subscribers.Include("_subscribedList"); 
+33
Dec 10
source share



All Articles