2013-10-27 3 views
0

다음과 같은 모델을 사용하고 있습니다. 먼저 Entity Framework 6 코드를 사용하여 응용 프로그램에서 사용하고 있습니다. 엔티티 프레임 워크 1 대 1 관계

public class Customer 
{ 
    public Customer 
    { 

    } 

    public int Id { get; set; } 
    public string Name { get; set; } 

    public virtual Address Address { get; set; } 
} 


public class Address 
{ 
    public Address 
    { 

    } 

    public int Id { get; set; } 
    public string Street { get; set; } 
    public int Number { get; set; } 
    public int Country { get; set; } 

    public virtual Customer Customer { get; set; }    
} 

내가 그들을 저장하려고

나는 다음과 같은 오류 얻을 :

Unable to determine the principal end of an association between the types Customer and Address

답변

3

당신은 외래 키 관계를 speicify 필요합니다. here과 같이 public virtual Customer Customer { get; set; }[ForeignKey("AddressId")]public virtual Address Address { get; set; } 이상으로 추가하고 해당 ID 필드를 모델에 추가하십시오. 그런 사람 :

public class Customer 
{ 
    public Customer 
    { 

    } 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public int Addressid { get; set; } 

    [ForeignKey("AddressId")] 
    public virtual Address Address { get; set; } 
} 


public class Address 
{ 
    public Address 
    { 

    } 

    public int Id { get; set; } 
    public string Street { get; set; } 
    public int Number { get; set; } 
    public int Country { get; set; } 
    public int CustomerId { get; set; } 

    [ForeignKey("CustomerId")] 
    public virtual Customer Customer { get; set; }    
} 
+0

그래, 그게 문제를 해결합니다. 고마워요! 한 가지 더 질문 : 유창한 API를 사용하여 달성 할 수 있다는 것을 읽었으며 고객 요청시 : HasRequired (c => c.Address) .WithRequiredPrincipal (a => a.Customer); 주소에 대해서도 똑같이하는 것입니까, 아니면 이것으로 충분합니까? 그리고 그것은 작동합니다 ... – user2818430

+0

외래 키가있는쪽에 정의되어야합니다. 예를 들어, 주소와 고객 모두 외래 키를 저장 한 상태에서 양측에 있어야합니다. – pcreech

관련 문제