我使用Entity Framework v4
的是(VS2010 Beta 2 附带的)+POCO
的。我可以完美地将数据库中的数据加载到 poco 中。
现在,我有一个 poco 实例,我不知道如何使用 EF4 将其保存到数据库中。有人可以帮忙吗?我猜这是因为 EF4 不知道 POCO 已经“改变”了?无论如何,这是我正在尝试的代码,但它不起作用。(它会插入数据库,但不会使用 Identity 值更新 POCO。)
(基于良好的 ole Northwind 数据库...)
public void Save(Category category)
{
// Error handling ommited...
bool isInsert = category.CategoryId <= 0;
// Note: Category is a POCO, not an entity object.
Category newCategory = isInsert
? new Category()
: ((from l in Context.Categories
.WithCategoryId(category.CategoryId)
select l).SingleOrDefault() ?? new Category());
// Left 2 Right.
newCategory.Name = category.Name;
// continue setting the properties.
// Context is a private property, representing the EF context.
Context.LogEntries.AddObject(newLogEntry);
Context.SaveChanges();
}
这段代码基于我对 Linq-To-Sql 所做的事情(效果很好!)一般逻辑流程是:-
- 获取现有对象。如果不存在,则创建一个新的。
- 设置此现有或新对象的所有属性。这会更新对象的状态。如果有任何更改,则该对象现在已被修改。否则它是新的。
- 保存对象。
那么,我可以用 EF4 重复这个概念吗?
干杯:)