簡體   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