更新实体框架 4.1 代码优先中的外键关联
我得出的结论是,我应该在我的代码优先设计中定义独立关联和外键关联。例如:
public class Book
{
public int ID {get; set;}
public int AuthorID {get; set;}
[ForeignKey("AuthorID")]
public Author Author {get; set;}
}
根据上面的定义,当我想更改书籍的作者时,我是否必须更新 AuthorID,或者只使用下面的行就足够了?
myBook.Author = 作者;如果这是我第一次为这本书定义作者,我会在上面的行中得到一个空异常吗? (当我给书的作者分配一些值时,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;
}
}
}
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您不能同时使用独立和外国键关联 - 您使用第一个或第二个。区别在于是否使用 FK 属性。如果使用外键关联,则应该使用外键来建立关系。这就是 EFv4 中引入 FK 关联的原因。
编辑:
简单的例子,为什么在使用自定义 POCO(EFv4.1 中常见)和 FK 关系时应该使用 FK 而不是导航属性:
这可以正常工作,没有任何问题:
这会引发异常:
这再次可以正常工作:
First of all you can't use both independent and foreign key association - you use either first or second. The difference is if you use FK property or not. If you use foreign key association you should use foreign key to build a relation. That is the reason why FK association was introduced in EFv4.
Edit:
Simple example why you should use FK instead of navigation property when using custom POCOs (common in EFv4.1) and FK relations:
This works without any problem:
This throws exception:
This again works without any problem:
下面的示例也存在同样的问题:
如果我将 Control 的属性绑定到 Player1Name 属性,则会收到 NullPointerException。在数据库中,我可以看到该表,它似乎具有正确的键值。
要解决该问题,只需替换
:
The example below has the same issue:
If I bind a property of a Control to the Player1Name property I get a NullPointerException. In the database I can see the table and it seems to have the correct key values.
To fix the problem just replace:
by