简体   繁体   中英

Updating using code first in Entity Framework 5 with detached entities

I am developing an n-tier application with detached entities (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 .

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.

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
  • Insert the new Cause into the dbContext

There is a flag IsCurrent in the Cause class; there will only be one record with that set to true ; it needs to be set to false if the new Cause is different to this one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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