实体框架的ASP.NET MVC [英] Entity Framework with ASP.NET MVC

查看:192
本文介绍了实体框架的ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用强类型的控制器,EntityObjects?

How can I use strongly-typed Controllers with EntityObjects?

我的错误...

首先我想这样的:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
    db.SaveChanges();
    return RedirectToAction("Index");
}

这没有实际保存任何更改到数据库。所以,我试图模型连接到我的ObjectContext:

This failed to actually save any changes to the database. So, I tried to attach the model to my ObjectContext:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
    db.Attach(Model);
    db.SaveChanges();
    return RedirectToAction("Index");
}

这失败,因为一个对象,一个空的EntityKey值不能附加到对象上下文。所以,我试图分配的EntityKey:

This failed because "an object with a null EntityKey value cannot be attached to an object context." So, I tried to assign the EntityKey:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
    Model.EntityKey = (from Department d in db.Department
                       where d.Id == id
                       select d).FirstOrDefault().EntityKey;
    db.Attach(Model);
    db.SaveChanges();
    return RedirectToAction("Index");
}

这失败,因为对象具有相同的键已经存在于ObjectStateManager的ObjectStateManager无法跟踪使用相同的密钥多个对象。

This failed because "an object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

这是如何工作的?

推荐答案

的事情是,你有什么作为你的输入是不是与改变的性质在一个完整的模型对象 - 它只是一个开始的新的,所有的要覆盖上一个已经存在的实体的属性。您没有张贴任何标识属性,

The thing is, what you have as your input is not a complete model object with changed properites - it is just a "start" of new one, with all the properties that you want to overwrite on an already existing entity. You don't post any of the ID properties,

这看起来有点冗长,但它是最好的,我已经找到了,所以我要做的事在我的项目(​​ajusted你的类名,与任何失踪了由...):

This looks a little verbose, but it's the best I've found, so it is how I do it in my projects (ajusted to your class names, with whatever was missing made up...):

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
    var dbDepartment = (from Department d in db.Department
                        where d.Id == id
                        select d).FirstOrDefault() as Department

    dbDepartment.Name = Model.Name;
    dbDepartment.Color = Model.Color;
    // etc, assigning values manually...

    try
    {
        db.SaveChanges();
    }
    catch (Exception ex)
    {
        // oops...
    }
    return RedirectToAction("Index");
}

这篇关于实体框架的ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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