我得出的结论是,我应该在我的代码优先设计中定义独立关联和外键关联。例如:
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;
}
}
}
首先你不能同时使用两者独立的外键关联- 您使用第一个或第二个。区别在于是否使用 FK 属性。如果使用外键关联,则应该使用外键来建立关系。这就是 EFv4 中引入 FK 关联的原因。
Edit:
使用自定义 POCO(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();
这又可以正常工作了:
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)