本文介绍了实体框架4.1 - 默认EntityState的FK?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,ASP.NET MVC和Entity Framework 4,我有一个名为UF,另外一个叫国家报的实体,他们有这样的关系:

  UF [* ... 0..1]派斯

我可以直接从UF使用导航属性访问派斯对象:

  UF.Pais.Whatever =foobar的;

目前我有一个观点这将插入一个新的项目到数据库中,并且它具有Pais.Codigo编辑(Codigo是派斯的主键)。所以,当我插入一个新的UF,框架创建UF类的实例,类派斯的一个实例的引用。那么这样做是:

 如果(ModelState.IsValid)
{
    db.UFs.AddObject(UF);
    db.SaveChanges();    返回查看();
}

的问题是,在EF被插入一个新派斯到数据库中,因此,它基本上忽略了现有

例如,如果让我们说我对象用友拥有一个派斯具有1的ID uf.Pais.Codigo的当前值是1,其他的属性,如描述,目前为空。当我执行的SaveChanges,无论是UF和uf.Pais是添加了的状态。对于uf.Pais正确的状态应该是不变的,因为它已经在数据库中存在。

我的问题是:有改变不改变默认的关系EntityState的一些方法?下面code解决了问题,但将它添加到每个功能与增加了一个新的条目添加到数据库(和每个FK)是矫枉过正!

  db.ObjectStateManager.ChangeObjectState(uf.Pais,EntityState.Unchanged);

就是这样。我不知道如果我是不够清楚。随意如果需要问的更多信​​息。很遗憾任何英文错误!

谢谢,

里卡多

PS:国家报表示国家与UF的国家


解决方案

Yes by calling Attach instead of Unchanged.

No it is not overkill, it is a solution because either Attach or AddObject will always make the operation for all entities and associations in entity graph. That means that calling AddObject will make everything what context is not aware of yet as Added and Attach will make everything what context is not aware of as Unchanged (so you will in turn have to set each modified or inserted entity to its correct state). That is how EF works if you are using detached entities.

Another solution for the problem is making the connection after the UF is added:

// Here UF.Pais is null
db.UFs.AddObject(uf);
// Create dummy Pais
var pais = new Pais { Id = "Codigo" };
// Make context aware of Pais
db.Pais.Attach(pais);
// Now make the relation
uf.Pais = pais;
db.SaveChanges();

If you are working with detached entities you are always responsible for setting the correct state for each entity (and independent association). So you will either use attached entities to let EF make the magic for you (as shown in the example) or you will use the approach you dislike. In more complex scenarios you can find out that best approach is to load entity graph again and merge incoming changes into the attached graph.

这篇关于实体框架4.1 - 默认EntityState的FK?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:24