我正在使用 EF4.0 编写一个 DAL 类,我已经阅读了
http://www.codeproject.com/Articles/43367/ADO-NET-Entity-Framework-as-Data-Access-Layer
和
http://msdn.microsoft.com/en-us/magazine/cc700340.aspx
但是当我测试他们的代码时,我遇到了更新和删除方法的一些问题。
DAL 类的所有代码如下所示:
public class FriendlinkDA : IDisposable
{
private EdiBlogEntities context;
public FriendlinkDA()
{
context = new EdiBlogEntities();
}
public void Dispose()
{
context.Dispose();
}
public FriendLink GetFriendLink(Guid id)
{
return context.FriendLink.FirstOrDefault(f => f.Id == id);
}
public void Update(FriendLink model)
{
// Way 1: (throw exception)
//context.Attach(model);
//model.SetAllModified(context);
//context.SaveChanges();
// Way 2:
EntityKey key;
object originalItem;
key = context.CreateEntityKey("FriendLink", model);
if (context.TryGetObjectByKey(key, out originalItem))
{
context.ApplyCurrentValues(key.EntitySetName, model);
//context.ApplyPropertyChanges(key.EntitySetName, model);
}
context.SaveChanges();
}
public void Delete(FriendLink model)
{
// Way 1:
context.Attach(model);
context.DeleteObject(model);
context.SaveChanges();
// Way 2:
//var item = context.FriendLink.FirstOrDefault(f => f.Id == model.Id);
//context.DeleteObject(item);
//context.SaveChanges();
}
}
扩展方法为:
public static void SetAllModified<T>(this T entity, ObjectContext context) where T : IEntityWithKey
{
var stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey);
var propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select
(pn => pn.FieldType.Name);
foreach (var propName in propertyNameList)
stateEntry.SetModifiedProperty(propName);
}
在应用程序中,我像这样使用 DAL:
// Delete
using (var optFriendlink = new FriendlinkDA())
{
var test = optFriendlink.GetFriendLink(new Guid("81F58198-D396-41DE-A240-FC306C7343E8"));
optFriendlink.Delete(test);
}
// Update
using (var optFriendlink = new FriendlinkDA())
{
var testLink = optFriendlink.GetFriendLink(new Guid("62FD0ACF-40C3-4BAD-B438-38BB540A6080"));
testLink.Title = "ABC";
optFriendlink.Update(testLink);
}
问题1:
在 Delete() 中,方式 1 和方式 2 都可以工作。哪一个更好?
问题2:
在 Update() 中,方式 1 给了我一个例外:对象无法附加,因为它已经在对象上下文中。仅当对象处于未更改状态时,才能重新附加对象。
关于此声明:上下文。附件(模型);
但是方式 2 很好。
为什么会这样?我还在 Delete() 中附加了模型,为什么 Delete() 工作正常?如何正确编写更新?
例外说明了一切:
仅当对象处于未更改状态时,才能重新附加对象。
您在 // Update
下的代码片段中更改对象,因此这就是无法重新附加它的原因。
至于哪种方法更好。通常,您会从上下文中获取对象,释放上下文,对对象执行某些操作,然后使用新上下文来保存对象。在这种情况下,使用 Attach
比先通过 Id 获取对象要舒服得多。