开发者

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 Conte开发者_如何学Cxt 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜