如何在数据库中更新模式,从asp.net MVC2,使用实体框架? [英] How to update model in the database, from asp.net MVC2, using Entity Framework?

查看:141
本文介绍了如何在数据库中更新模式,从asp.net MVC2,使用实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立ASP.NET MVC2应用程序,并使用实体框架的ORM。我有麻烦更新数据库中的对象。每次我尝试entity.SaveChanges(),EF插入表中的新生产线,无论做我想做的更新,或插入工作要做。我想(在接下来的例子等)对象的实体连接,但后来我得到了

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();
    }

我甚至用AttachTo(汽车总动员,汽车)试过,但我得到了同样的异常。

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

任何人有经验,用这个?

Anyone has experience with this?

推荐答案

如果您正在更新现有的记录,那么你应该有你正在为你的InsertOrUpdate方法的对象实例中的EntityKey。回到你的code和看看你能不能找到这何处迷路。我怀疑你是presenting用户提供了一个表单更新此对象,然后映射响应领域回一个Car对象,但你不及格与它的EntityKey(您可能不希望显示它给用户)。

If you are updating an existing record then you should have the EntityKey within the object instance you are providing to your InsertOrUpdate method. Go back to your code and see if you can locate where this is getting lost. I'd suspect you are presenting the user with a form to update this object and then mapping the response fields back into a Car object but you aren't passing the EntityKey with it (you probably don't want to display it to the user).

什么你需要做的是包括使用隐藏的输入型形式的关键。您可以使用HTML辅助Html.Hidden(键字段名键字段值),以确保它传递到用户表格,然后回到你的帖子code。

What you'd need to do is to include the Key in the form using an input type of 'hidden'. You can use the Html helper Html.Hidden("Key field name", key field value) to ensure it's passed to the user form and then back to your Post code.

这篇关于如何在数据库中更新模式,从asp.net MVC2,使用实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆