Hi folks,
I've using Entity Framework v4
(that comes with VS2010 Beta 2) + POCO
's. I can load the data from the db into the poco's perfectly.
Now, i have a single poco instance, and i don't know how to save it to the DB, using EF4. Can someone help please? I'm guessing it's because the EF4 doesn't know that the POCO has 'changed'? anyways, here's the code i was TRYING and it doesn't work. (it does an insert into the db, but doesn't update the POCO with the Identity value.)
(based upon the good ole Northwind database...)
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();
}
This code is based on what I do with Linq-To-Sql (which works great!) The general logic flow is :-
- Get existing object. if none exists, then create a new one.
- set all the properties on this existing or new object. This UPDATES the state of the object. if there's anything that is changed, the object is now modified. otherwise it's new.
- save object.
So, can i repeat this concept with EF4?
cheers :)