开发者

Adding the same items to many-to-many relation in EF 4.0

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:

Adding the same items to many-to-many relation in EF 4.0

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?


You cannot do that with many-to-many relation. You must model your Configuration_Hardware as separate entity with one-to-many relations to Configuration and Hardware.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜