I have come to a conclusion that I should define both Independent Association and Foreign Key Association in My Code-First design. e.g:
public class Book
{
public int ID {get; set;}
public int AuthorID {get; set;}
[ForeignKey("AuthorID")]
public Author Author {get; set;}
}
With the above definition, do I have to update AuthorID when I want to change the book's author, Or just using the below line is enough?
myBook.Author = author;Am I going to get a null exception on the above line if that is the first time I'm defining an author for the book? (Does EF initialize book's author automatically when I assign some value to it?) Should I initialize it in the definition:
The code:
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;
}
}
}