如何使用Entity Framework从asp.net MVC2更新数据库中的模型?

时间:2010-04-27 10:54:38

标签: asp.net-mvc entity-framework asp.net-mvc-2

我正在构建ASP.NET MVC2应用程序,并使用Entity Framework作为ORM。我在更新数据库中的对象时遇到了麻烦。每次我尝试entity.SaveChanges()时,EF都会在表中插入新行,无论我是否想要更新,或者插入都要完成。我尝试将(如下一个例子中)对象附加到实体,但后来我得到了

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

这是我用于插入和更新的简单功能(它不是关于车辆的,但是这样解释起来更简单,尽管我认为这种效果根本没有答案)......

        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(“汽车”,汽车),但我得到了同样的例外。

任何人都有这方面的经验吗?

3 个答案:

答案 0 :(得分:3)

我可以给你一个粗略的指导,但你上面的代码并没有给我一些工作。

您可能希望执行以下操作:

using(Entities dataModel = new Entities())
{
    if(car.Id == 0 || car.Id == null)
    {
        dataModel.AddToCars(car); /* There should be a generated method similar to 
        this that just takes a car object minus the Primary Key */
    }
    else
    {
        var selectedCar = dataModel.Cars.Where(x => x.Id == car.Id).FirstOrDefault();

        if(selectedCar != null)
        {
            selectedCar.Name == car.Name; 
            // Continue updating your car stuff
        }
    }

    dataModel.SaveChanges();
}

答案 1 :(得分:1)

如果要更新现有记录,则应在要为InsertOrUpdate方法提供的对象实例中包含EntityKey。回到你的代码,看看你是否可以找到丢失的地方。我怀疑你是在向用户提供一个表单来更新这个对象,然后将响应字段映射回Car对象,但是你没有用它传递EntityKey(你可能不希望将它显示给用户)。

您需要做的是使用输入类型“隐藏”在表单中包含Key。您可以使用Html帮助程序Html.Hidden(“键字段名称”,键字段值)来确保将其传递给用户表单,然后再返回到您的邮政编码。

答案 2 :(得分:1)

有些人可能认为更优雅的另一种方法是:

IContext context = ContextFactory.GetContext();
EntityRepo repo = new EntityRepo(context); //Entity Repository
OtherTableEntity y = new OtherTableEntity() //this could be some other derived value you already have 
//that uniquely identifies the record (or foreign key or other value you want to update)
Int32 id = 1234; //value to update to
var z = repo.TableToUpdate.List().Where(x => x.FK_ID == y.FK_ID).FirstOrDefault();
if (z != null)
{
     z.FK_ID = id;
     repo.Commit();
 }

repo.Commit();之前和之后休息一下,打开SQL查询窗口,在repo.Commit()之前和之后运行一个表格选择。

添加标准基本上是您想要的。致电repo.EntityToUpdate.Add(entity)repo.Commit()

相关问题