用于更改跟踪的Web API和OData?

时间:2014-10-31 08:52:04

标签: c# asp.net-web-api odata

我目前正在使用Web APi 2控制器,DTO(使用AutoMapper)和单独的服务层。我的DAL使用EF6实现UoW和通用存储库模式。典型的控制器如下所示:

public class CustomerTypeController : EntityController<DTO.CustomerType>
{
    private readonly ICustomerTypeService customerTypeService;

    public CustomerTypeController(ICustomerTypeService customerTypeService)
    {
        this.customerTypeService = customerTypeService;
    }

    public override IHttpActionResult Get(int id)
    {
        var item = Mapper.Map<DTO.CustomerType>(customerTypeService.Get(id));
        return Ok<DTO.CustomerType>(item);
    }

    public override IHttpActionResult Create(DTO.CustomerType customerType)
    {
        return Save(customerType);
    }

    public override IHttpActionResult Update(DTO.CustomerType customerType)
    {
        return Save(customerType);
    }

    private IHttpActionResult Save(DTO.CustomerType customerType)
    {
       var customerTypeModel = Mapper.Map<DTO.CustomerType>(customerTypeService.Save(Mapper.Map<Model.CustomerType>(customerType)));
       return Ok<DTO.CustomerType>(customerType);
    }

    public override IHttpActionResult Delete(int id)
    {
        customerTypeService.Delete(id);
    }
}

这是一个简单实体的控制器。我有一些实体,它们具有许多嵌套导航级别的复杂性。

使用当前的解决方案,由于webapi的RESTful特性,我无法利用EF的更改跟踪。因此,当我将更新保存回数据库时,EF会生成包含所有字段的UPDATE查询。这显然不是我想要的,因为:

  1. 只应将更改的列发送到数据库
  2. 我的实体审核未捕获更改的列及其值。
  3. 所以基本上我目前正在为模型设计师(我先使用数据库)和阅读表格使用EF6。这看起来有点矫枉过正。

    因此,要解决我的更改跟踪问题,我需要使用ChangeTracking或TrackableEntities等软件包。我想避免这些,因为我不想在客户端添加额外的引用或产生更大的有效负载。

    或者,我可以将OData的Delta与WebAPI一起使用,尽管我已经读过它与JSON不能很好地兼容。此外,我也使用Jil和ProtoBuf媒体格式化器。

    最后一个解决方案是完全使用OData控制器。但我想为我的控件保持相同的结构,如上所示。我对OData的分页,过滤,排序等不感兴趣。

    在这个阶段,如果这解决了我的更改跟踪问题,我可能会决定完全使用OData。

    这是唯一可行的方法,还是有替代方法或解决方法?

0 个答案:

没有答案