views:

237

answers:

2

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 :-

  1. Get existing object. if none exists, then create a new one.
  2. 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.
  3. save object.

So, can i repeat this concept with EF4?

cheers :)

+1  A: 

Are you sure the state has been changed?
You may want to check out Context.DetectChanges()

http://msdn.microsoft.com/en-us/library/dd456854(VS.100).aspx

devlife
+1  A: 

In EF you'll need to use Attach for existing (updating) objects instead of AddObject for new (inserting) objects. Other than that it should work.

Craig Stuntz
yeah. ha! i didn't know it was that simple :) and now i'm using the Unit Of Work pattern, it's actually really really awesome :)
Pure.Krome