2011-04-19 2 views
3

My Code-First 디자인에서 Independent Association과 Foreign Key Association을 모두 정의해야한다는 결론에 도달했습니다. 예컨대 : 위의 정의와Entity Framework 4.1의 외래 키 연결 업데이트 코드 우선

public class Book 
{ 
    public int ID {get; set;} 
    public int AuthorID {get; set;} 
    [ForeignKey("AuthorID")] 
    public Author Author {get; set;} 
} 
  1. , 나는이 책의 저자를 변경하려면, 또는 바로 아래 라인이 충분히 사용할 때이 AuthorID를 업데이트해야합니까?
    myBook.Author = author;

  2. 내가이 책의 저자를 정의하는 것이 처음이라면 위의 줄에 null 예외가 발생합니까? (내가 몇 가지 값을 할당 할 때합니까 EF는 자동으로이 책의 저자를 초기화?) 나는 정의에 초기화해야 :

코드 : 모든

public class Book 
{ 
    public int ID {get; set;} 
    public int AuthorID {get; set;} 

    private Author m_Author; 
    [ForeignKey("AuthorID")] 
    public Author Author {get 
    { 
    get 
    { 
     if (m_Author == null) 
     m_Author = new Author(); 
     return m_Author; 
    } 
    set 
    { 
     this.m_Author = value; 
    } 
    } 
} 

답변

4

먼저 당신이 모두를 사용할 수 없습니다 independent and foreign key association - 첫 번째 또는 두 번째 중 하나를 사용합니다. 차이점은 FK 속성을 사용하는지 여부입니다. 외래 키 연관을 사용하는 경우 외래 키를 사용하여 관계를 만들어야합니다. 그것이 FK 협회가 EFv4에 도입 된 이유입니다.

편집 :

(EFv4.1에서 공통) 사용자 정의 포항 강판 및 FK 관계를 사용할 때 대신 탐색 속성의 FK를 사용해야하는 이유

간단한 예 :

var child = new ChildEntity() {Id = 1}; 
child.ParentEntityId = 1; // Assigning FK 
context.Childs.Attach(child); 
context.Entry(child).State = EntityState.Modified; 
context.SaveChanges(); 
:이 문제없이 작동

을 법과

var parent = new ParentEntity() { Id = 1 }; 
context.Parents.Attach(parent); 
var child = new ChildEntity() {Id = 1}; 
child.Parent = parent; // <-- Assigning only navigation property 
// Next line will cause InvalidOperationException: 
// A referential integrity constraint violation occurred: 
// The property values that define the referential constraints 
// are not consistent between principal and dependent objects in 
// the relationship. 
context.Childs.Attach(child); 
context.Entry(child).State = EntityState.Modified; 
context.SaveChanges(); 

이 다시 :

이 예외가 발생합니다 아무 문제없이 KS :

var parent = new ParentEntity() { Id = 1 }; 
context.Parents.Attach(parent); 
var child = new ChildEntity() {Id = 1}; 
child.Parent = parent; 
child.ParentEntityId = 1; // <-- AGAIN assigning FK 
context.Childs.Attach(child); 
context.Entry(child).State = EntityState.Modified; 
context.SaveChanges(); 
+1

가에서 "만들기 및 수정 관계"에서 두 번째 예를 살펴 보시기 바랍니다 : HTTP : // MSDN을 .microsoft.com/kr/library/ee373856.aspx 탐색 속성을 할당해도 예외가 throw되지 않는 이유는 무엇입니까? (두 번째 예제에서는 navigatrion 속성 만 업데이트됩니다.) – Kamyar

2

의 예는 다음과 같은 문제가있다 : 나는 NullPointerException이 얻을 Player1Name 속성에 컨트롤의 속성을 바인딩 할 경우

public class PingPongPlayer 
{ 
    [Key] 
    public string Name { get; set; } 
    public string EMail { get; set; } 
    public int Ranking { get; set; } 
} 

public class Match 
{ 
    [Key] 
    public int Id { get; set; } 

    public string FrkPlayer1 { get; set; } 
    public string FrkPlayer2 { get; set; } 

    [ForeignKey("FrkPlayer1")] 
    public PingPongPlayer Player1 { get; set; } 

    [ForeignKey("FrkPlayer2")] 
    public PingPongPlayer Player2 { get; set; } 

    public DateTime MatchDate { get; set; } 

    public bool AlreadyPlayed { get; set; } 

    public string Player1Name 
    { 
     get { return Player1.Name; } 
    } 

    public string Player2Name 
    { 
     get { return Player2.Name; } 
    } 
} 

합니다. 데이터베이스에서 나는 테이블을 볼 수 있으며 올바른 키 값을 가진 것으로 보인다.

Name EMail Ranking <br> 
a [email protected] 10 <br> 
b [email protected] 15 <br> 
c [email protected] 12 <br> 
d [email protected] 20 <br> 

Id FrkPlayer1 FrkPlayer2 MatchDate AlreadyPlayed 
1 a   b   2011-04-21 00:00:00.000 0 
2 a   c   2011-04-21 00:00:00.000 0 
3 b   c   2011-04-21 00:00:00.000 0 
4 a   d   2011-04-21 00:00:00.000 0 
5 a   c   2011-04-21 00:00:00.000 0 
6 d   c   2011-04-21 00:00:00.000 0 

문제를 해결하기 위해 단지 대체 :

[ForeignKey("FrkPlayer1")] 
public PingPongPlayer Player1 { get; set; } 

[ForeignKey("FrkPlayer2")] 
public PingPongPlayer Player2 { get; set; } 

에 의해
[ForeignKey("FrkPlayer1")] 
public virtual PingPongPlayer Player1 { get; set; } 

[ForeignKey("FrkPlayer2")] 
public virtual PingPongPlayer Player2 { get; set; } 
+0

흠! 게으른 로딩을 사용하는 방법에 대한 팁을 주셔서 감사합니다. – Kamyar