繁体   English   中英

自定义值类型,EF代码优先和路由

[英]Custom value type, EF Code First and routing

在我们的WebApi项目中,我们使用EF CodeFirst方法。 另外,我们使用两种类型的数据库:SQL Server和MySQL。 所有表都有字段ID ,但是在SQL Server数据库中,此字段具有int数据类型,在MySQL数据库中,此字段为char(36)并包含GUID

为了解决这个问题,我创建了一个像IdType这样的自定义值类型,并更改了所有模型类以使用该类型insted int

public class Document
{
  public IdType ID { get; set; }
  public string DocumentNm { get; set; }
  ...
}

然后,我配置了DbContext(例如,对于SQL Server)

modelBuilder.Properties<IdType>().Configure(c => c.HasColumnType("int"));

...并更改存储库:

public interface IRepository<T> where T : IEntity
{
  IQueryable<T> GetAll();
  T GetById(IdType id);
  ...
}

之后,当我尝试转到例如http://localhost:7081/api/Document ,它给了我一个错误:

找到多个与请求匹配的操作:\\ r \\ nWebUI.Controllers.API.DocumentController类型的\\ r \\ nGetById WebUI.Controllers.API.DocumentController类型的

我使用路由的默认设置。 这是DocumentController的[HttpGet]方法:

public HttpResponseMessage Get() { ... }
public HttpResponseMessage GetById(IdType id) { ... }

我该如何解决这个问题? 这可能是IdType实施不正确的IdType吗?

PS我按此处所述为int值创建了IdType。 如果需要添加更多信息,请告诉我。

UPDATE

DocumentController:

public HttpResponseMessage GetById(IdType id)
{
    var entity = repository.GetById(id);

    if (entity == null)
    {                
       return ErrorMsg(HttpStatusCode.NotFound, string.Format("No {0} with ID = {1}", GenericTypeName, id););
    }

    return Request.CreateResponse(HttpStatusCode.OK, entity);
 }

我的资料库:

 public virtual T GetById(IdType id)
 {
    return GetAll().FirstOrDefault(x => x.ID == id);
 }
 public virtual IQueryable<T> GetAll()
 {
   return entities = context.Set<T>();
 }

似乎在当前版本的Entity Framework中尚未实现

正如GitHub上的任务中所述

我们目前正计划在我们最初的EF7 RTM之后启用此功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM