How to update model in the database, from asp.net MVC2, using Entity Framework?

Posted by Eedoh on Stack Overflow See other posts from Stack Overflow or by Eedoh
Published on 2010-04-27T10:54:37Z Indexed on 2010/04/27 11:23 UTC
Read the original article Hit count: 1108

Hello.

I'm building ASP.NET MVC2 application, and using Entity Framework as ORM. I am having troubles updating object in the database. Every time I try entity.SaveChanges(), EF inserts new line in the table, regardless of do I want update, or insert to be done. I tried attaching (like in this next example) object to entity, but then I got

{"An object with a null EntityKey value cannot be attached to an object context."}

Here's my simple function for inserts and updates (it's not really about vehicles, but it's simpler to explain like this, although I don't think that this effects answers at all)...

        public static void InsertOrUpdateCar(this Vehicles entity, Cars car)
    {
        if (car.Id == 0 || car.Id == null)
        {
            entity.Cars.AddObject(car);
        }
        else
        {
            entity.Attach(car);
        }
        entitet.SaveChanges();
    }

I even tried using AttachTo("Cars", car), but I got the same exception.

Anyone has experience with this?

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about asp.net-mvc