[英]LINQ to Entity Framework queries in a generic controller
我正在嘗試為Web Api編寫通用控制器,但遇到了這個問題,LINQ to EF不喜歡我的工作。
這是我嘗試過的。
這是默認控制器:
public class DefaultController<TEntity> : ApiController where TEntity : class, IEntity
{
private AppEntities Context;
private DbSet<TEntity> AppDbSet;
public DefaultController()
{
Context = new AppEntities();
AppDbSet = Context.Set<TEntity>();
}
public IHttpActionResult Get(int Id)
{
var entity = AppDbSet.Where(x => x.IdValue == Id);
if (entity == null)
return NotFound();
return Ok(entity);
}
}
因此,我決定創建一個接口:
public interface IEntity
{
int IdValue { get; }
}
數據庫的第一種方法是為每個表生成一個.cs文件,然后在單獨的文件中添加一些內容:
public partial class User : IEntity
{
public int IdValue
{
get
{
return this.Id;
}
}
}
這似乎可以明智地進行編譯,但是在運行時會失敗。
The specified type member 'IdValue' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
因此,我試圖弄清楚如何在通用控制器的LINQ查詢中引用上下文實體的屬性,但這失敗了。
有任何想法嗎 ?
PS:我知道通用控制器可能會出現問題,但是我想學習如何在簡單模型方便使用的情況下制作一個。
如果要使用帶有Id的基本接口,則應將具有此屬性的所有實體映射到db中的column。 不應有類似的代理屬性
public int IdValue
{
get
{
return this.Id;
}
}
所以你應該創建界面
public interface IEntity
{
int Id{ get; }
}
並且所有繼承的實體都應具有此屬性
public partial class User : IEntity
{
public int Id{get; set;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.