如何使用实体框架和映射器更新/编辑数据库字段

本文关键字:更新 编辑 数据库 字段 映射 何使用 实体 框架 | 更新日期: 2023-09-27 18:20:01

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

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

注意:"地址地址"类已经有地址。Id字段。

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

如何使用实体框架和映射器更新/编辑数据库字段

在这种情况下,您可以不使用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或任何映射实用程序,因为我们没有将数据模型映射到视图模型(或沿着这些线做任何事情)。