[英]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>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.