【问题标题】:How to update an entity using Entity Framework from Business Layer?如何使用业务层中的实体框架更新实体?
【发布时间】:2014-06-30 06:59:35
【问题描述】:

我的 Web 应用程序由 3 层、控制器、业务逻辑和存储库构成。

从 BL 层,我正在使用以下代码更新实体。如您所见,我正在逐个更新属性。

我想知道是否有更好的方法来做到这一点,删除这个手动映射。

---------- 控制器

    public IHttpActionResult Put(int id, DeviceDTO dto)
    {
        GaDevice device = Mapper.Map<GaDevice>(dto);
        deviceBLL.Update(id, device);
        return Ok();
    }

---------- BL

    public void Update(int id, GaDevice entity)
    {
        bool hasValidId = GetById(id) != null ? true : false;
        if (hasValidId == true)
        {
            GaDevice device = deviceRepo.GetById(id);
            device.CanNotifyPc = entity.CanNotifyPc; // NOT SURE HERE
            device.CanNotifyPrinter = entity.CanNotifyPrinter;
            device.LocationId = entity.LocationId;
            device.Name = entity.Name;
            device.Note = entity.Note;
            device.OperativeFromTime = entity.OperativeFromTime;
            device.OperativeToTime = entity.OperativeToTime;
            deviceRepo.Update(device );
            deviceRepo.Save();
        }

---------------- 存储库

    public void Update(GaDevice entity)
    {
        context.Entry(entity).State = EntityState.Modified;
    }

【问题讨论】:

  • 你试过 device=entity ???
  • deviceRepo.Update你可以在设置状态之前附加设备。顺便说一句,恕我直言,映射应该在存储库中,而不是在 BL 中。恕我直言,在域和存储库中使用业务类可以节省时间,但会增加混乱。

标签: c# entity-framework entity-framework-5


【解决方案1】:

如何将对context 所做的更改保存在Update() 中? 否则,Save() 中的代码会做什么?

public void Update(GaDevice entity)
{
    context.Entry(entity).State = EntityState.Modified;
    context.SaveChanges();
}

【讨论】:

    猜你喜欢
    • 2016-09-24
    • 2011-08-11
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多