简体   繁体   English

通用控制器中的LINQ to Entity Framework查询

[英]LINQ to Entity Framework queries in a generic controller

I'm trying to write a generic controller for a Web Api and I'm running into this one problem, LINQ to EF doesn't like what I do. 我正在尝试为Web Api编写通用控制器,但遇到了这个问题,LINQ to EF不喜欢我的工作。

Here's what I've tried. 这是我尝试过的。

Here's the default controller: 这是默认控制器:

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);   
    }
}

So I've decided to create an interface: 因此,我决定创建一个接口:

public interface IEntity
{
    int IdValue { get; }
}

And the database first approach generates a .cs file for each table, and I add some meat to it in a separate file: 数据库的第一种方法是为每个表生成一个.cs文件,然后在单独的文件中添加一些内容:

public partial class User : IEntity
{
    public int IdValue
    {
        get
        {
            return this.Id;
        }
    }
}

This seems to work compilation wise, but fails at runtime. 这似乎可以明智地进行编译,但是在运行时会失败。

The specified type member 'IdValue' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

So I'm trying to figure out how I could refer to my context entities's properties in a LINQ queries in the generic controller, but this fails. 因此,我试图弄清楚如何在通用控制器的LINQ查询中引用上下文实体的属性,但这失败了。

Any ideas ? 有任何想法吗 ?

PS: I'm aware generic controller can become problematic, but I'd like to learn how to make one in the event where it can become handy for simple models. PS:我知道通用控制器可能会出现问题,但是我想学习如何在简单模型方便使用的情况下制作一个。

If you want base interface with Id, you should have all entities with this property mapped to column in db. 如果要使用带有Id的基本接口,则应将具有此属性的所有实体映射到db中的column。 There should not be proxy properties like 不应有类似的代理属性

    public int IdValue
    {
        get
        {
            return this.Id;
        }
    }

So you should create interface 所以你应该创建界面

public interface IEntity
{
    int Id{ get; }
}

And all your inherited entities should have this property 并且所有继承的实体都应具有此属性

public partial class User : IEntity
{
    public int Id{get; set;}
}

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

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