这应该是一个简单的涉及EF代码的第一,但我不能包装我的头周围的文档,我发现所有的例子是从旧版本。我正在使用最新的(4.1)。EF代码优先与两个DbContexts
反正我有一些车型,如:
public class Foo
{
public int ID { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public int ID { get; set; }
public string Value { get; set; }
}
我使用了一些脚手架与Asp.Net MVC创建我的控制器/存储库,当我创建一个“富”的对象,还创建了一个“酒吧”对象,即使我从存储在数据库中的东西设置'Bar'属性。
public class FooViewModel
{
public int ID { get; set; }
public int BarID { get; set; }
}
public ActionResult Create(FooViewModel foo)
{
var entity = new Foo()
{
ID = foo.ID,
Bar = _barRepository.Find(foo.BarID)
};
_fooRepository.InsertOrUpdate(entity);
_fooRepository.Save();
// more stuff
}
如何使用EF的流利语法来阻止它在数据库中创建新的'Bar'行?
更新
这里是生成的库代码:
public void InsertOrUpdate(Foo foo)
{
if (foo.ID == default(int)) {
// New entity
context.Foo.Add(foo);
} else {
// Existing entity
context.Foo(foo).State = EntityState.Modified;
}
}
public void Save()
{
context.SaveChanges();
}
您的_fooRepository和_barRepository共享相同的数据库上下文实例吗? –
Doh ......是的,那是问题所在。我在想,它会查看Bar对象的主键而不是一些神奇的EF实体跟踪。另外,我认为这两个存储库会共享一个上下文。当我添加IOC时,我可以设置它来做到这一点。如果你愿意的话,你可以回答这个问题,这样我就可以关闭它。 –