开发者

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

My model looks like this

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

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 开发者_如何学CWithout including Address.


It's the model validation of DbContext which complains apparently. 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). 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. 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:

public virtual Address Address{get;set;}

EF will then lazy-load the address when needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜