简体   繁体   中英

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.

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:

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.

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.

If you want base interface with Id, you should have all entities with this property mapped to column in db. 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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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