【问题标题】:How to Update/Edit Database Field with Using Entity Framework and Mapper如何使用实体框架和映射器更新/编辑数据库字段
【发布时间】:2012-01-12 07:28:20
【问题描述】:

这是一个具体的问题。我们正在使用 C#、EF4.1 和 Mapper 编写 wcf 服务。 我们不想使用存储过程……无论如何;问题是,我们要编辑 db 上的地址字段。但是我们无法将编辑后的地址保存到数据库中。

    public int EditAddress(int userId, Address address)
    {
        using(var mobileServiceContext = new MobileServiceContext())
        {
            Address oldAddress = mobileServiceContext.Addresses.FirstOrDefault(p => p.UserId == userId && p.AddressId == address.AddressId);
            Address lastAddress = Mapper.Map(address, oldAddress);

            //save new-last address with ? HOW ?
            //mobileServiceContext.Addresses.Attach(updatedAddress); //doesn't work
            mobileServiceContext.SaveChanges();
        }

        return address.AddressId;
    }

这是我们编辑的函数;

    public int EditAddress(int userId, Address address)
    {
        using(var mobileServiceContext = new MobileServiceContext())
        {
            Address oldAddress = mobileServiceContext.Addresses.FirstOrDefault(p => p.UserId == userId && p.AddressId == address.AddressId);
            Address lastAddress = Mapper.Map(address, oldAddress);

            mobileServiceContext.Addresses.Attach(lastAddress); //error on this line
            mobileServiceContext.ObjectStateManager.ChangeObjectState(lastAddress, EntityState.Modified);
            mobileServiceContext.SaveChanges();
        }

        return address.AddressId;
    }

注意:“地址地址”类已经有 address.Id 字段。

我们在这里制作的设计非常复杂,读者也很难阅读。

【问题讨论】:

    标签: c# wcf entity-framework-4 automapper


    【解决方案1】:

    在这种情况下,您可以执行以下操作,而不是使用 AutoMapper:

    //this assumes that the AddressId in address is exists in the database: just attach it to the addresses set
    mobileServiceContext.Addresses.Attach(address);
    //this tells ef that the object is in a modified state
    mobileServiceContext.ObjectStateManager.ChangeObjectState(address, entityState.Modified);
    //savechanges will now update the database
    mobileServiceContext.SaveChanges();
    

    我认为这里不需要 AutoMapper 或任何映射实用程序,因为我们没有将数据模型映射到视图模型(或做任何类似的事情)。

    【讨论】:

    • 非常感谢您的回答。它一次性起作用。当我们尝试第二次工作时;我们收到此错误; ( on ...Addresses.Attach(address); )“ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。”并且内部异常中没有有用的信息
    • @LostInLib - 没问题 :) 抱歉,我只看了评论的第一部分。
    • 您是否尝试将同一个对象两次附加到同一个上下文(即一次调用中)?
    • 我更新了我的问题。我们没有附加相同的对象/我们没有使用附加或其他方法来编辑对象...我也尝试禁用映射器 //Address lastAddress = Mapper.Map(address, oldAddress);但没有运气......无论如何,非常感谢你。你的回答是对的,它可以在干净的代码上工作。 (我们的 EditAddress 方法使用了大约 30 种方法才能到达这里 =))
    猜你喜欢
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多