简体   繁体   English

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

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

My model looks like this我的 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*/
}

Now suppose i have created a person with proper address, in future when i try to update person like this现在假设我已经创建了一个具有正确地址的人,将来当我尝试更新这样的人时

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

It gives error saying Address is required.它给出了错误说地址是必需的。

So to avoid this iam including Address property too while loading Person Entity因此,为了避免这个 iam 在加载 Person Entity 时也包括 Address 属性

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

Is there any way i can update person Without including Address .有什么办法可以在不包括Address的情况下更新person

It's the model validation of DbContext which complains apparently.显然是抱怨的DbContext的 model 验证。 So, one solution would be to switch off this validation:因此,一种解决方案是关闭此验证:

dbContext.Configuration.ValidateOnSaveEnabled = false;

The other option is to introduce a foreign key property:另一种选择是引入外键属性:

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*/
}

You can omit the [Required] attribute here because EF will detect the relationship as required by convention (due to the non-nullable FK property).您可以在此处省略[Required]属性,因为 EF 将按照约定检测关系(由于不可为空的 FK 属性)。 This works also with enabled validation.这也适用于启用的验证。

The behaviour is a bit confusing since EF doesn't send a change of the FK column to the database, so there is not really a constraint violation and the Update command executes fine.这种行为有点令人困惑,因为 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). 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).

If you want the address to be automatically loaded by EF 4.1 you have to make the Address-porperty virtual:如果您希望 EF 4.1 自动加载地址,则必须将地址端口设为虚拟:

public virtual Address Address{get;set;}

EF will then lazy-load the address when needed.然后,EF 将在需要时延迟加载地址。

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

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