简体   繁体   English

使用分离的实体首先在Entity Framework 5中使用代码进行更新

[英]Updating using code first in Entity Framework 5 with detached entities

I am developing an n-tier application with detached entities (Visual Studio 2010). 我正在开发一个带有分离实体的n层应用程序(Visual Studio 2010)。 I have not included the class definitions as they seem irrelevant to the logic. 我没有包含类定义,因为它们似乎与逻辑无关。

The following code snippet works correctly and is embedded in a using dbContext . 以下代码段正常工作,并嵌入在using dbContext

dbContext.Entry(Case).State = Case.CaseID == 0 ? EntityState.Added : EntityState.Modified;
dbContext.Entry(Case.Woman).State = Case.Woman.CaseID == 0 ? EntityState.Added : EntityState.Modified;
dbContext.Entry(Case.Summary).State = Case.Summary.CaseID == 0 ? EntityState.Added : EntityState.Modified;

dbContext.SaveChanges();

I have added a collection ICollection<Cause> Causes to the Summary class. 我在Summary类中添加了一个集合ICollection<Cause> Causes

What I want to do is: 我想做的是:

  • Check to see if a new Cause is the same as the most recently saved Cause , and, if so, change the value of a flag in the saved Cause 检查新Cause是否与最近保存的Cause相同,如果是,则更改已保存Cause中的标志值
  • Insert the new Cause into the dbContext 将新Cause插入dbContext

There is a flag IsCurrent in the Cause class; Cause类中有一个标志IsCurrent ; there will only be one record with that set to true ; 只有一条记录设置为true ; it needs to be set to false if the new Cause is different to this one. 如果新Cause与此Cause不同,则需要将其设置为false

I would welcome a code-first based way of doing this. 我会欢迎以代码优先的方式来做这件事。

Something like this should work: 这样的事情应该有效:

using (...)
{
    Cause c = db.Causes.FirstOrDefault(ce => ce.IsCurrent == true);
    if (cause.Title != c.Title)
    {
        c.IsCurrent = false;
        cause.IsCurrent = true;        
    }

    //
    // other codes ...
    //
}

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

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