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

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

问题描述

我很好奇是否可以通过包含对象映射一个中间表.

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 代码优先中映射私有属性.这里很好地描述了如何做吧.在您的情况下,它是关于 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 是私有的.

It won't compile, because _subscribedList is private.

你可以做的是在Subscriber中创建一个嵌套的映射类:

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 保护为虚拟的,以允许延迟加载.但是甚至可以使用 Include 进行预加载:

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天全站免登陆