EF 4.1 Fluent API。如何在使用具有三个id列的现有连接表时映射两个实体?

时间:2012-01-16 17:38:46

标签: entity-framework entity-framework-4.1 mapping fluent-interface

我在代码中有三个实体(EntityA,EntityB,EntityC)以及它们在数据库中的各自表(TableA,TableB,TableC)。我还有一个现有的连接表,它有三个ID列(TableA_ID,TableB_ID,TableC_ID)。

在代码中,实体的关联如下:

MODELS:
public class EntityA
{
   public Guid EntityA_ID { get; set }
   .....
   // Each EntityA can be associated with 0 or Many EntityB
   public virtual ICollection<EntityB> EntityBCollection { get; set; }
}

public class EntityB
{
   public Guid EntityB_ID { get; set; }
   .....
   // Each EntityB can be associated with 0 or Many EntityA
   public virtual ICollection<EntityA> EntityACollection { get; set; }

   // Each EntityB can be assocated with 0 or Many EntityC,
   // but it becomes 0 or 1 when EntityB is associated with an EntityA
   public virtual EntityC EntityC { get; set; }
}

public class EntityC
{
   public Guid EntityC_ID { get; set; }
   ......
   // Each EntityC an only be associated with a EntityB
   // an EntityC does not exist on its own
   public virtual EntityB EntityB { get; set; }
}

DATA CONTEXT:
modelBuilder.Entity<EntityB>()
                .HasOptional(entityb => entityb.EntityC)
                .WithRequired(entityc => entityc.EntityB)
                .Map(map =>
                {
                    map.ToTable("ThreeIDColumnJoinTable").MapKey(new string[]{"EntityA_ID", "EntityB_ID", "EntityC_ID"});

                });

我一直收到以下错误:

Unable to determine the principal end of an association between the types 'EntityC' and 'EntityB'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. 

关于如何在DATA CONTEXT中重新配置映射的任何想法,以便它不会产生错误,它还将包括在ThreeIDColumnJoinTable中指定的EntityA的关系?

1 个答案:

答案 0 :(得分:0)

  

//每个EntityB可以与0或许多EntityC关联,但当EntityB与EntityA关联时,它变为0或1

在这种情况下,您的EntityB具有错误的导航属性。它应该是:

public class EntityB
{
   public Guid EntityB_ID { get; set; }
   .....
   // Each EntityB can be associated with 0 or Many EntityA
   public virtual ICollection<EntityA> EntityACollection { get; set; }

   public virtual ICollection<EntityC> EntityCCollection { get; set; }
}

您需要收集EntityC以支持&#34;许多&#34;部分。数据库/模型无法强制执行规则的第二部分。它必须由您的应用程序逻辑强制执行。

您的模型的其余部分可以按原样使用。删除那个流畅的映射,你应该得到A和B之间的多对多关系以及B和C之间的一对多关系。这正是你的规则所说的。

对于三个表,没有什么比自动多对多更好的了。如果您需要(不是您当前的情况),您必须将联结表映射为第四个实体,并将其他三个实体的导航属性映射到提供关系桥的新实体。