简体   繁体   中英

Entity Framework keeps ghost entities?

Let's make this simple... Suppose I have 2 entities:

Application
   Id: int (primary key, autoincrement)
   Name: string(60)
   Client: User
   SupportEngineer: User

 User
  Id: int (primary key, autoincrement)
  Name: string(60)
  EmailAddress: string(60)

Suppose also I have a method named Create that is receiving an instance of Application created (in another layer) without the Context beign involved:

var application = new Application
       {
          Name = "Visual Studio 2010",
          Client = new User { Id = 12 },
          SupportEngineer = new User { Id = 14 }
       };

Note that User with Id == 12 and == 14 exists in the database!!

public void Create(Application application) {
    application.Client = Context.Users.FirstOrDefault(e => e.Id == application.Client.Id);
    application.SupportEngineer = Context.Users.FirstOrDefault(e => e.Id == application.SupportEngineer.Id);
    Context.Applications.AddObject(application);
    Context.SaveChanges();
  }

When I inspect the objects in the Context before the call to SaveChanges, I get the User objects created before calling the Create method as "added".

Why that is happening if I'm overriding the values of the properties Client and SupportEngineer with objects from the database? Why the mannually created objects ( new User { Id = 12 }, new User { Id = 14 } ) are still around, moreover in the context with "added" state?

Just do this:

var application = new Application
   {
      Name = "Visual Studio 2010",
      ClientId = 12,
      SupportEngineerId = 14
   };

And have the Create method just create the object:

public void Create(Application application) {
    Context.Applications.AddObject(application);
    Context.SaveChanges();
}

Not a direct answer but some general advise:

Another thing you might want to watch out for, it looks as if you're reusing your DbContext. This is generally a bad idea, especially when adding/deleting objects. For example after a delete, the deleted objects are still known by the context. Instead I'd recommend a pattern like:

using(var ctx = new MyContext())
{
    ctx.Applications.Add(application);
    ctx.SaveChanges();
}

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