【问题标题】:LINQ to Entity Framework queries in a generic controller通用控制器中的 LINQ to Entity Framework 查询
【发布时间】:2015-12-20 20:43:57
【问题描述】:

我正在尝试为 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:我知道通用控制器可能会出现问题,但我想学习如何制作一个,以便它可以方便地用于简单模型。

【问题讨论】:

    标签: c# .net entity-framework-6 asp.net-web-api2


    【解决方案1】:

    如果您想要带有 Id 的基本接口,您应该将所有具有此属性的实体映射到 db 中的列。不应该有像

    这样的代理属性
        public int IdValue
        {
            get
            {
                return this.Id;
            }
        }
    

    所以你应该创建接口

    public interface IEntity
    {
        int Id{ get; }
    }
    

    你所有继承的实体都应该有这个属性

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      相关资源
      最近更新 更多