让我们这么简单...... 假设我有2个实体:
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)
假设我还有一个名为Create的方法,它正在接收一个Application实例(在另一个层中)而没有涉及Context beign:
var application = new Application { Name = "Visual Studio 2010", Client = new User { Id = 12 }, SupportEngineer = new User { Id = 14 } };
请注意,数据库中存在Id == 12和== 14的用户!!
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(); }
当我在调用SaveChanges之前检查Context中的对象时,我在将Create方法调用为“added”之前创建了User对象。
如果我使用数据库中的对象覆盖Client和SupportEngineer属性的值,为什么会发生这种情况?
为什么手动创建的对象(new User { Id = 12 }, new User { Id = 14 }
)仍然存在,而且在具有“添加”状态的上下文中?
答案 0 :(得分:0)
这样做:
var application = new Application
{
Name = "Visual Studio 2010",
ClientId = 12,
SupportEngineerId = 14
};
让Create方法只创建对象:
public void Create(Application application) {
Context.Applications.AddObject(application);
Context.SaveChanges();
}
不是直接答案,而是一些一般性建议:
您可能需要注意的另一件事,看起来好像您正在重复使用DbContext。这通常是一个坏主意,特别是在添加/删除对象时。例如,在删除之后,上下文仍然知道已删除的对象。相反,我推荐一种类似的模式:
using(var ctx = new MyContext())
{
ctx.Applications.Add(application);
ctx.SaveChanges();
}