好的这个让我疯了!我在这做错了什么?插入操作有效,但更新没有......提前谢谢!
if (mFromXml.Any()) {
using (DBDataContext DB = new DBDataContext()) {
foreach (object m_loopVariable in mFromXml) {
m = m_loopVariable;
XSLive mToDb = new XSLive();
mToDb.Id = m.Id;
mToDb.Location = m.Location;
XS.XSLive existingMInDb = (from c in DB.XSLive where c.Id == mToDb.Id).FirstOrDefault();
if (existingMInDb != null) {
existingMInDb = mToDb;
} else {
DB.XSLive.InsertOnSubmit(mToDb);
}
}
DB.SubmitChanges();
}
}
答案 0 :(得分:1)
问题是您要用新对象按引用替换现有的MIDDb对象。结果是整个existingMInDb变量现在指向mToDb。由Entity Framework跟踪的旧的existingMInDb对象已经消失。
您需要在existingMInDb对象上单独更新属性。你需要改变:
if (existingMInDb != null) {
existingMInDb = mToDb;
}
要:
if (existingMInDb != null) {
existingMInDbId.Id = mToDb.Id;
existingMInDbId.Location = mToDb.Location;
}