实体框架多对多关系

时间:2014-10-29 18:26:27

标签: asp.net entity-framework

好的,我正在试图弄清楚如何正确设置我的数据库。

我有两个班级:

public class Event
{
    public int EventId { get; set; }
    public string EventName { get; set; }
}

public class Dog
{
    public int DogId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

活动必须能够包含一系列狗。 每只狗都必须能够参与任何活动。 我猜这是他们所谓的多对多关系,但我现在不知道如何用钥匙等设置它。我希望我能够清楚地知道我希望的是什么实现。

昨天我问了一个类似的问题但我当时并不清楚我需要什么: Have a list of objects as a foreign key

谢谢!

3 个答案:

答案 0 :(得分:3)

是的,这是N:N关系。假设代码优先,更改您的实体:

public class Event
{
    public Event()
    {
       Dogs = new HashSet<Dog>();
    }
    public int EventId { get; set; }
    public string EventName { get; set; }
    public virtual ICollection<Dog> Dogs { get; set; }
}

public class Dog
{
    public Dog()
    {
       Events = new HashSet<Event>();
    }
    public int DogId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual ICollection<Event> Events { get; set; }
}

您的OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Dog>()
    .HasMany(d => d.Events)
    .WithMany(e => e.Dogs)
    .Map(m =>
    {
       m.MapLeftKey("DogId");
       m.MapRightKey("EventId");
       m.ToTable("DogEvent");
    });
}

然后应该只使用两个外键DogEventDogId

创建一个联结表EventId

答案 1 :(得分:2)

每个班级你应该只需要一个ICollection<T>属性:

public class Event
{
    public int EventId { get; set; }
    public string EventName { get; set; }

    public virtual ICollection<Dog> Dogs { get; set; }
}

public class Dog
{
    public int DogId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public virtual ICollection<Event> Events { get; set; }
}

EF应该能够处理多对多关系,而无需您明确定义映射,但如果您想自己设置联结表,则可以通过覆盖OnModelCreating方法(如在其他答案中解释)。

答案 2 :(得分:2)

它仍然与你昨天的问题非常相似。有关该主题的好博文,请参阅http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First

public class Event
{
    public int EventId { get; set; }
    public string EventName { get; set; }

    public ICollection<Dog> Dogs { get; set; }

    public Event()
    {
        Dogs = new HashSet<Dog>();
    }

}

public class Dog
{
    public int DogId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public ICollection<Event> Events { get; set; }

    public Dog()
    {
        Events = new HashSet<Dog>();
    }
}

上面代码(以及之前的问题)背后的想法是,狗可以拥有与其相关联的事件的“集合”,并且事件可以具有与其相关联的狗的集合。