2013-11-26 39 views
1

我有一个简单的对象,可以是父组对象的子对象。复杂的是,父组可以是两个“类型”(不是C#类型)中的一个,由enum属性指示,每个子对象只能在每个类型中的一个中。这可能会与类更有意义:在实体框架中设置相同对象之间的2个关系

public class Child 
    { 
     public string Value { get; set; } 
     public int? ParentGroup1Id{ get; set; } 
     public int? ParentGroup2Id { get; set; } 
     public ParentGroup ParentGroup1 { get; set; } 
     public ParentGroup ParentGroup2 { get; set; } 
    } 

    public class ParentGroup 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public GroupType GroupType { get; set; } 
     public IList<Child> Children1 { get; set; } 
     public IList<Child> Children2 { get; set; } 
    } 

我已经建立了针对儿童的EF地图:

public class ChildMap : EntityTypeConfiguration<Child> 
    { 
     public ChildMap() 
     { 
      HasKey(t => t.Value); 

      HasOptional(c => c.ParentGroup1) 
      .WithMany(pg => pg.Children1) 
      .HasForeignKey(c => c.ParentGroup1Id); 

      HasOptional(c => c.ParentGroup2) 
      .WithMany(pg => pg.Children2) 
      .HasForeignKey(c => c.ParentGroup2Id); 
     } 
    } 

在我的背景下,我已在DBSets两个对象了:

public IDbSet<Child> Children { get; set; } 
    public IDbSet<ParentGroup> ParentGroups { get; set; } 

当我去那个访问数据库的页面时,我得到以下错误:

Additional information: Schema specified is not valid. Errors: The relationship 'ServiceLayer.Contexts.Child_ParentGroup' was not loaded because the type 'ServiceLayer.Contexts.ParentGroup' is not available.

顺便说一句,一切都在ServiceLayer命名空间中。

我猜想,它不认为这些是有效的关系,但我不够好与EF知道如何设置这种关系。有没有办法让这个工作,还是我必须完全改变它?

回答

1

感谢提供的答案here,我拿出WithMany调用的内容,并且解决了它。

所以,我ChildMap现在看起来是这样的:

public class ChildMap : EntityTypeConfiguration<Child> 
    { 
      public ChildMap() 
      { 
      HasKey(t => t.Value); 

      HasOptional(c => c.ParentGroup1) 
       .WithMany() 
       .HasForeignKey(c => c.ParentGroup1Id); 

      HasOptional(c => c.ParentGroup2) 
       .WithMany() 
       .HasForeignKey(c => c.ParentGroup2Id); 
     } 
    } 

我猜测,给它一个参数尝试设置的关系了两个方向,并在ParentGroup儿童藏品过于含糊。

我现在有一个ParentGroupMap建立从最终的关系(的东西,我在最初的尝试都试过,但它并没有与ChildMap工作):

public class ParentGroupMap : EntityTypeConfiguration<ParentGroup> 
    { 
     public ParentGroupMap() 
     { 
      HasMany(pg => pg.Children1) 
       .WithOptional(c => c.ParentGroup1) 
       .HasForeignKey(c => c.ParentGroup1Id); 

      HasMany(pg => pg.Children2) 
       .WithOptional(c => c.ParentGroup2) 
       .HasForeignKey(c => c.ParentGroup12d); 
     } 
    } 
相关问题