繁体   English   中英

首先 Enitify Framework 代码:使用所需的相关导航属性更新实体

[英]Enitify Framework code first: Updating Entity With required related navigational property

我的 model 看起来像这样

public Class Address 
{
     public int Id {get;set;}

     /*Props here*/
}

public Class Person
{
     public int Id {get;set;}

     public String Name {get;set;}

     [Required]      
     public Address Address{get;set;}

     /*More props*/
}

现在假设我已经创建了一个具有正确地址的人,将来当我尝试更新这样的人时

var person= db.Persons.FirstOrDefault(p=>p.Id=1234);
person.Name="Foo";
db.SaveChanges();

它给出了错误说地址是必需的。

因此,为了避免这个 iam 在加载 Person Entity 时也包括 Address 属性

var person= db.Persons.Include(p=>p.Address).FirstOrDefault(p=>p.Id=1234);
person.Name="Foo";
db.SaveChanges();

有什么办法可以在不包括Address的情况下更新person

显然是抱怨的DbContext的 model 验证。 因此,一种解决方案是关闭此验证:

dbContext.Configuration.ValidateOnSaveEnabled = false;

另一种选择是引入外键属性:

public class Person
{
    public int Id {get;set;}
    public String Name {get;set;}
    public int AddressId {get;set;}
    public Address Address {get;set;}

    /*More props*/
}

您可以在此处省略[Required]属性,因为 EF 将按照约定检测关系(由于不可为空的 FK 属性)。 这也适用于启用的验证。

这种行为有点令人困惑,因为 EF 不会将 FK 列的更改发送到数据库,因此实际上并没有违反约束并且 Update 命令执行得很好。 I guess that the validation just checks the state of the model in memory (invalid, because Address is null) and not the state the model would have in the database when SaveChanges did execute (valid, because FK is correctly set).

如果您希望 EF 4.1 自动加载地址,则必须将地址端口设为虚拟:

public virtual Address Address{get;set;}

然后,EF 将在需要时延迟加载地址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM