EF Code First关系0/1到0/1与不同的父母

时间:2014-10-01 11:23:26

标签: entity-framework ef-code-first code-first ef-migrations

我在EF CodeFirst和关系0/1到0/1方面遇到了一些问题。我有3"表"包含另一个,这是可选的。

它类似于:

[DataContract]
public class A
{  
    [DataMember, Key]
    public int Id {get;set;}
    [DataMember]
    public int? IdD
    [ForeignKey("idD")]
    public virtual D D {get; set;}
} 
[DataContract] 
public class B
{  
    [DataMember, Key]
    public int Id {get;set;}
    [DataMember]
    public int? IdD
    [ForeignKey("idD")]
    public virtual D D {get; set;}
}
[DataContract]
public class C
{  
    [DataMember, Key]
    public int Id {get;set;}
    [DataMember]
    public int? IdD
    [ForeignKey("idD")]
    public virtual D D {get; set;}
}    
[DataContract]
public class D
{
    [DataMember, Key]
    public int Id {get;set;}

    public virtual A A { get; set; }
    public virtual B B { get; set; }
    public virtual C C { get; set; }
}

当我尝试进行迁移时,出现错误:

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

我尝试使用DataAnnotations和Fluent API并出现相同的错误。在Fluent API上我尝试:

与A,B或C类

        this.HasOptional(casv => casv.D)
            .WithOptionalDependent(e => e.A)//I try with denendent and Principal
            .Map(m => m.MapKey("IdD")) // I try without this
            .WillCascadeOnDelete(true);

1 个答案:

答案 0 :(得分:0)

试试这个,我觉得它比你的代码看起来更好看:

this.HasOptional(casv => casv.D)
    .WithOptionalDependent(e => e.A)
    .Map(m => m.MapKey("IdD"))
    .WillCascadeOnDelete(true);