实体框架通过包含对象多对多 [英] Entity Framework Many to many through containing object

查看:154
本文介绍了实体框架通过包含对象多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,如果有可能通过一个包含对象映射到一个中间表。

I was curious if it is possible to map an intermediate table through a 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 subscriber table, channel table and an intermediate table to link a subscriber to his/her channels.

是否有可能映射列表是ChannelList对象认购模式中?

Is it possible to map the list that is within the ChannelList object to the Subscriber Model?

我想这可能是不可能的,而且我需要只是有一个私人名单EF映射。但我不知道,如果EF会替私有变量。会这样吗?

I figured that's probably not possible and that I would need to just have a private List for EF to map. But I wasn't sure if EF will do that for private variables. Will it?

我希望是不会,因为如果它是公共保持封装。

I'm hoping that is does because if it has to be public to maintain the encapsulation.

推荐答案

您可以映射EF code-第一家民营性质。 <一href=\"http://blog.oneunicorn.com/2012/03/26/$c$c-first-data-annotations-on-non-public-properties/\">Here是一个很好的说明如何做到这一点。你的情况是关于 Subscriber._subscribedList 的映射。你不能做到这一点(在上下文的覆盖 OnModelCreating

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);

这不会编译,因为 _subscribedList 是私人的。

你可以做的是用户创建一个嵌套映射类:

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);
        }
    }
}

OnModelCreating

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

您可能希望 _subscribedList 受保护的虚拟,允许延迟加载。但是,它甚至可以做到预先加载与包含

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");

这篇关于实体框架通过包含对象多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆