在 EF 4.0 中将相同的项目添加到多对多关系
我的域模型中有两个实体:
public class Configuration : DomainEntity
{
public virtual ICollection<Hardware> Hardwares { get; set; }
public Configuration()
{
Hardwares = new List<Hardware>();
}
}
public class Hardware : DomainEntity
{
public virtual ICollection<Configuration> Configurations { get; set; }
public Hardware()
{
Configurations = new HashSet<Configuration>();
}
}
数据库中有三个表。我绑定这些表:
modelBuilder.Entity<Configuration>().
HasMany<Hardware>(configuration => configuration.Hardwares).
WithMany(hardware => hardware.Configurations).
Map(map => map.ToTable("tblConfiguration_Hardware"));
它工作正常,但是......当我添加相同的硬件时,例如三个硬件,我获取数据库中的一条记录。
Hardware hardware = db.Find<Hardware>(hardwareID);
configuration.Hardwares.Add(hardware); // first
configuration.Hardwares.Add(hardware); // second
configuration.Hardwares.Add(hardware); // third
db.Add<Configuration>(configuration);
db.SaveChanges();
但我想挽救三个关系。我做错了什么?
I have two entities in my domain model:
public class Configuration : DomainEntity
{
public virtual ICollection<Hardware> Hardwares { get; set; }
public Configuration()
{
Hardwares = new List<Hardware>();
}
}
public class Hardware : DomainEntity
{
public virtual ICollection<Configuration> Configurations { get; set; }
public Hardware()
{
Configurations = new HashSet<Configuration>();
}
}
And I have three tables in database. I bind these tables:
modelBuilder.Entity<Configuration>().
HasMany<Hardware>(configuration => configuration.Hardwares).
WithMany(hardware => hardware.Configurations).
Map(map => map.ToTable("tblConfiguration_Hardware"));
And it work fine, but... When I add the same hardwares, for example three hardwares, I get one record in database.
Hardware hardware = db.Find<Hardware>(hardwareID);
configuration.Hardwares.Add(hardware); // first
configuration.Hardwares.Add(hardware); // second
configuration.Hardwares.Add(hardware); // third
db.Add<Configuration>(configuration);
db.SaveChanges();
But I want to save three relations. What do i wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法通过多对多关系来做到这一点。您必须将
Configuration_Hardware
建模为与Configuration
和Hardware
具有一对多关系的单独实体。它不起作用的原因是,与隐藏联结表的多对多关系期望联结表中使用的 FK 形成复杂的 PK,但在您的情况下,您有单独的 PK,因此您必须将其映射为单独的实体。
You cannot do that with many-to-many relation. You must model your
Configuration_Hardware
as separate entity with one-to-many relations toConfiguration
andHardware
.The reason why it doesn't work is that many-to-many relation with hidden junction table expects that FKs used in junction table forms complex PK but in your case you have separate PK and so you must map it as separate entity.