EntityFramework多表对多表 [英] EntityFramework Mutli-Table Many-to-Many

查看:190
本文介绍了EntityFramework多表对多表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF4.1 Code First,正在尝试创建一些多对多关系表,在该表中需要链接这些表.请在下面看到一小段代码:

I'm working with EF4.1 Code First and am trying to create some Many-to-Many relationship tables where there tables would need to be linked. Please see small snippet of code beloow:

class Event
{
    int EventId { get; set; }
    ICollection<Contact> Contacts { get; set; }
}

class Contact
{
    int ContactId { get; set; }
    ICollection<Relation> Relations { get; set; }
}

class Relation
{
    int RelationId { get; set; }
    string Name { get; set; }
}   

因此,Contacts对象可以具有许多不同类型的关系,例如母亲",父亲",兄弟"等.

So the Contacts object can have many different types of Relationship, such as "Mother", "Father", "Brother", etc.

我需要跟踪联系人参加的某种活动,但是我想知道他与主持活动的人有何关系.例如,他是Eventer的兄弟,父亲还是丈夫?在另一事件中,可能是同一个人出现,但是Eventer的兄弟姐妹.

要联系的事件是多对多;与联系人的关系是一对多的.

Event to Contact is Many-to-Many; Relation to Contact is One-to-Many.

在SQL中,我们将创建一个链接表,并在其中具有所有三个属性ID(EventId,ContactId,RelationId);但是,在Code First中,您如何表示这种关系?

In SQL, we would just made a link table and have all three properties Id's there (EventId, ContactId, RelationId); however, in Code First, how would you represent this relationship?

推荐答案

与数据库相同,您必须创建一个映射实体,就像ContactEvents一样,例如数据库中的映射表.

Same as database you have to create a mapping entity just like ContactEvents like mapping table in database.

class Event
{
  int EventId { get; set; }
  ICollection<ContactEvent> ContactEvents { get; set; }
}

class ContactEvent
{
  int EventId {get;set;}
  int ContactId {get;set;}
  public virtual Event Event {get; set;}
  public virtual Contact Contact {get;set;}
}

class Contact
{
   int ContactId { get; set; }
   ICollection<ContactEvent> ContactEvents { get; set; }
   ICollection<Relation> Relations { get; set; }
}

class Relation
{
  int RelationId { get; set; }
  string Name { get; set; }
  public virtual Contact Contact {get; set}
}   

这篇关于EntityFramework多表对多表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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