2012-04-23 3 views
1
[Table("Table1")] 
    public class Entity1 
    { 
     [Key, ForeignKey("entity1")] 
     public int ID{get;set;} 
     public virtual Entity2 entity2{get;set;} 
     public virtual Entity3 entity3{get;set;} 
    } 


이것은 내 주요 엔터티입니다. 여기 엔 Entity2와 3의 Entity를 Entity1,2,3의 기본 키인 동일한 외래 키로 매핑하려고합니다. EF에서 공유 외래 키 사용 방법

[Table("Table3")] 
    public class Entity3 
    { 
     [Key] 
     public int Entity1ID{get;set;} 
     // few entity specific properties 
    } 


매핑 내 상황에 맞는 클래스를 사용하는 것입니다


[Table("Table2")] 
    public class Entity2 
    { 
     [Key] 
     public int Entity1ID{get;set;} 
     // few entity specific properties 
    } 


는 당신이 같은 이름을 가진 두 가지 속성을 가질 수 없습니다 the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must

답변

2
modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2) 
          .WithRequired(); 
     modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2) 
          .WithRequired(); 


위가 할 수있는 여분의 아무것도 아니다, 그래서 주석 속성을 제거합니다.

-1

오류가 말한다받을 수 있습니다. 이것을 시도하십시오 :

[Table("Table1")] 
public class Entity1 
{ 
    [Key, ForeignKey("Entity2"), ForeignKey("Entity3")] 
    pubic int ID{get;set;} 
    public virtual Entity2 Entity2{get;set;} 
    public virtual Entity3 Entity3{get;set;} 
} 

Btw. 그것은 매우 이상한 디자인처럼 보입니다. 만, 다음 코드를 사용하여 기본 키 관계를 공유가 필요하면

+0

오류 : 중복 외래 키 속성 – RollerCosta

+0

내 질문이 – RollerCosta

+0

업데이트되었습니다.이 경우 속성 대신 Fluent API를 사용해보십시오. –