c# - OData $expand、DTO 和 Entity Framework

标签 c# entity-framework asp.net-web-api odata

我有一个基本的 WebApi 服务设置,其中数据库首先设置了 EF DataModel。我正在运行 WebApi、EF6 和 WebApi OData 包的夜间构建。 (WebApi:5.1.0-alpha1,EF:6.1.0-alpha1,WebApi OData:5.1.0-alpha1)

数据库有两个表:Product 和 Supplier。一个产品可以有一个供应商。供应商可以有多个产品。

我还创建了两个 DTO 类:

public class Supplier
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual IQueryable<Product> Products { get; set; }
}

public class Product
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

我已按如下方式设置我的 WebApiConfig:

public static void Register(HttpConfiguration config)
{
    ODataConventionModelBuilder oDataModelBuilder = new ODataConventionModelBuilder();

    oDataModelBuilder.EntitySet<Product>("product");
    oDataModelBuilder.EntitySet<Supplier>("supplier");

    config.Routes.MapODataRoute(routeName: "oData",
        routePrefix: "odata",
        model: oDataModelBuilder.GetEdmModel());
}

我已经按如下方式设置了我的两个 Controller :

public class ProductController : ODataController
{
    [HttpGet]
    [Queryable]
    public IQueryable<Product> Get()
    {
        var context = new ExampleContext();

        var results = context.EF_Products
            .Select(x => new Product() { Id = x.ProductId, Name = x.ProductName});

        return results as IQueryable<Product>;
    }
}

public class SupplierController : ODataController
{
    [HttpGet]
    [Queryable]
    public IQueryable<Supplier> Get()
    {
        var context = new ExampleContext();

        var results = context.EF_Suppliers
            .Select(x => new Supplier() { Id = x.SupplierId, Name = x.SupplierName });

        return results as IQueryable<Supplier>;
    }
}

这是返回的元数据。如您所见,导航属性设置正确:

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
 <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <Schema Namespace="StackOverflowExample.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
   <EntityType Name="Product">
    <Key>
     <PropertyRef Name="Id" />
    </Key>
    <Property Name="Id" Type="Edm.Int32" Nullable="false" />
    <Property Name="Name" Type="Edm.String" />
   </EntityType>
   <EntityType Name="Supplier">
    <Key>
     <PropertyRef Name="Id" />
    </Key>
    <Property Name="Id" Type="Edm.Int32" Nullable="false" />
    <Property Name="Name" Type="Edm.String" />
    <NavigationProperty Name="Products" Relationship="StackOverflowExample.Models.StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner" ToRole="Products" FromRole="ProductsPartner" />
   </EntityType>
   <Association Name="StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner">
    <End Type="StackOverflowExample.Models.Product" Role="Products" Multiplicity="*" />
    <End Type="StackOverflowExample.Models.Supplier" Role="ProductsPartner" Multiplicity="0..1" />
   </Association>
  </Schema>
  <Schema Namespace="Default" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
   <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
    <EntitySet Name="product" EntityType="StackOverflowExample.Models.Product" />
    <EntitySet Name="supplier" EntityType="StackOverflowExample.Models.Supplier" />
     <AssociationSet Name="StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartnerSet" Association="StackOverflowExample.Models.StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner">
      <End Role="ProductsPartner" EntitySet="supplier" />
      <End Role="Products" EntitySet="product" />
     </AssociationSet>
    </EntityContainer>
   </Schema>
  </edmx:DataServices>
</edmx:Edmx>

所以正常的 odata 查询数组工作正常:例如/odata/product?$filter=Name+eq+'Product1' 和/odata/supplier?$select=Id 都工作正常。

问题是当我尝试使用 $expand 时。如果我要执行/odata/supplier?$expand=Products,我当然会得到一个错误:

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

更新: 我不断收到相同的问题,所以我添加了更多信息。是的,导航属性设置正确,如我在上面发布的元数据信息中所示。

这与 Controller 上缺少的方法无关。如果我要创建一个实现 IODataRoutingConvention 的类,/odata/supplier(1)/product 将被解析为“~/entityset/key/navigation”就好了。

如果我要完全绕过我的 DTO 并只返回 EF 生成的类,则 $expand 可以开箱即用。

更新 2: 如果我将我的产品类别更改为以下内容:

public class Product
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual Supplier Supplier { get; set; }
}

然后将 ProductController 更改为:

public class ProductController : ODataController
{
    [HttpGet]
    [Queryable]
    public IQueryable<Product> Get()
    {
        var context = new ExampleContext();

        return context.EF_Products
            .Select(x => new Product() 
            { 
                Id = x.ProductId, 
                Name = x.ProductName, 
                Supplier = new Supplier() 
                {
                    Id = x.EF_Supplier.SupplierId, 
                    Name = x.EF_Supplier.SupplierName 
                } 
            });
    }
}

如果我调用/odata/product,我会得到预期的结果。响应中未返回具有供应商字段的产品数组。 sql 查询从 Suppliers 表生成连接和选择,如果不是下一个查询结果,这对我来说很有意义。

如果我调用/odata/product?$select=Id,我会得到我期望的结果。但是 $select 转换为不连接供应商表的 sql 查询。

/odata/product?$expand=Product 失败并出现不同的错误:

"The argument to DbIsNullExpression must refer to a primitive, enumeration or reference type."

如果我将 Product Controller 更改为以下内容:

public class ProductController : ODataController
{
    [HttpGet]
    [Queryable]
    public IQueryable<Product> Get()
    {
        var context = new ExampleContext();

        return context.EF_Products
            .Select(x => new Product() 
            { 
                Id = x.ProductId, 
                Name = x.ProductName, 
                Supplier = new Supplier() 
                {
                    Id = x.EF_Supplier.SupplierId, 
                    Name = x.EF_Supplier.SupplierName 
                } 
            })
            .ToList()
            .AsQueryable();
    }
}

/odata/product、/odata/product?$select=Id 和/odata/product?$expand=Supplier 返回正确的结果,但显然 .ToList() 有点违背了目的。

我可以尝试将 Product Controller 修改为仅在传递 $expand 查询时调用 .ToList(),如下所示:

    [HttpGet]
    public IQueryable<Product> Get(ODataQueryOptions queryOptions)
    {
        var context = new ExampleContext();

        if (queryOptions.SelectExpand == null)
        {
            var results = context.EF_Products
                .Select(x => new Product()
                {
                    Id = x.ProductId,
                    Name = x.ProductName,
                    Supplier = new Supplier()
                    {
                        Id = x.EF_Supplier.SupplierId,
                        Name = x.EF_Supplier.SupplierName
                    }
                });

            IQueryable returnValue = queryOptions.ApplyTo(results);

            return returnValue as IQueryable<Product>;
        }
        else
        {
            var results = context.EF_Products
                .Select(x => new Product()
                {
                    Id = x.ProductId,
                    Name = x.ProductName,
                    Supplier = new Supplier()
                    {
                        Id = x.EF_Supplier.SupplierId,
                        Name = x.EF_Supplier.SupplierName
                    }
                })
                .ToList()
                .AsQueryable();

            IQueryable returnValue = queryOptions.ApplyTo(results);

            return returnValue as IQueryable<Product>;
        }
    }
}

不幸的是,当我调用/odata/product?$select=Id 或/odata/product?$expand=Supplier 时,它会引发序列化错误,因为 returnValue 无法转换为 IQueryable。如果我调用/odata/product,我可以被转换。

这里的工作是什么?我是否只需要跳过尝试使用我自己的 DTO,或者我可以/应该推出我自己的 $expand 和 $select 实现吗?

最佳答案

基本问题已在 EF 6.1.0 中修复。参见 https://entityframework.codeplex.com/workitem/826 .

关于c# - OData $expand、DTO 和 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323545/

相关文章:

asp.net - 如何自定义 ASP.NET Web API AuthorizeAttribute 以满足异常需求

c# - WebAPI DTO 响应请求消息传递模式

c# - 为什么 Stack<T> 和 Queue<T> 用数组实现?

c# - 从 ASP.NET WEB API 调用 Angular 路由

c# - 在 Linq 查询中调用方法

c# - 使用 Mock、Repository 和 UnitOfWork C# UnitTesting 测试 BLL

entity-framework - 使用 Entity Framework 的数据安全

C# enum 如何检查枚举中是否存在描述

c# - rc1.final 中的 User.Identity 中不存在 getUserId

c# - "GetBy"Web API中的方法