好吧,我正在尝试弄清楚如何正确设置我的数据库。
我有两节课:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
}
and
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
一个事件必须能够包含一组狗。
每只狗都必须能够参加任何活动。
我猜这就是他们所谓的多对多关系,但我现在不知道如何使用密钥等设置它。我希望我足够清楚我希望实现的目标。
我昨天问了类似的问题,但当时我不清楚我需要什么:将对象列表作为外键.
Thanks!
是的,这就是 N:N 关系。假设 Code First,更改您的实体:
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
and EventId
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)