假设我的表中有一行:
| ID | Name |
| 1 | file1.doc |
我想更新该行中的 Name 列,所以我使用该代码:
public partial class Adapter
{
private my_Entities _db = null;
public my_Entities db
{
get
{
if (_db == null) _db = new my_Entities();
return _db;
}
}
public Orders GetOrderByID(int id)
{
return (from x in db.Orders
where x.ID == id
select x).FirstOrDefault();
}
}
Adapter adapter = new Adapter();
var order = adapter.GetPublishOrderByID(123);
for(int i = 0; i < 2; i++) //< 2 is just for test, the purpose of the whole code is to append the FileName if any file exist for the order
{
var existingFile = order.Files.FirstOrDefault();
//here I get the information about entries
var objectStateEntries = adapter.db.ObjectStateManager.
GetObjectStateEntries(EntityState.Added |
EntityState.Modified |
EntityState.Unchanged);
if (existingFile != null)
{
//now, in the objectStateEntries I can see that ont item with the Added state,
//and the another entity with the Modified state.
//They're poining at the same entity (the same ID)
existingFile.FileName = "lorem.doc"; //FileName is 'file1.doc'
}
else
{
order.P_CoverOptionalTempFiles.Add(new P_Files{ FileName = "file1.doc" });
//the row's State is Added
}
adapter.db.SaveChanges();
}
现在在我的数据库中我看到两行
| ID | Name |
| 1 | file1.doc |
| 2 | lorem.doc |
为什么 ?