实体框架许多一对多的关系 [英] Entity framework many-to-many relationship
问题描述
好吧,我想弄清楚如何设置我的数据库正常。
Ok, I'm trying to figure out how to setup my DB properly.
我有两个类:
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; }
}
的事件必须能够包含狗的集合。
每只狗必须能够在任何情况下的部分。
我猜这就是他们所谓的很多一对多的关系,但是我现在该怎么用钥匙等。我希望我是什么,我希望达到足够清晰设置它没有。
An event must be able to contain a collection of dogs. Every dog must be able to be part in any event. I'm guessing this is what they call a many-to-many relationship, but I do not now how to set it up with keys etc. I hope I'm clear enough with what I'm hoping to achieve.
昨天我问过类似的问题,但我当时没有结束,我需要什么明确的:
有对象作为一个外键的列表。
I asked a similar question yesterday but I was then not clear over what I needed: Have a list of objects as a foreign key.
谢谢!
推荐答案
是的,这是一个N:N的关系。假设code首先,改变你的实体:
Yes, that is a N:N relationship. Assuming Code First, change your entities:
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");
});
}
这应该然后创建一个路口表 DogEvent
只用两个外键, DogId
和 EVENTID
This should then create a junction table DogEvent
with just the two foreign keys, DogId
and EventId
这篇关于实体框架许多一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!