【发布时间】:2015-08-02 03:15:42
【问题描述】:
我正在尝试使用实体框架、WebAPI、OData 和 Angular 客户端组合一个简单的玩具项目。一切正常,除了我放在我的一个模型上的导航属性似乎没有工作。当我使用 $expand 调用我的 API 时,返回的实体没有导航属性。
我的班级是 Dog 和 Owner,看起来像这样:
public class Dog
{
// Properties
[Key]
public Guid Id { get; set; }
public String Name { get; set; }
[Required]
public DogBreed Breed { get; set; }
public int Age { get; set; }
public int Weight { get; set; }
// Foreign Keys
[ForeignKey("Owner")]
public Guid OwnerId { get; set; }
// Navigation
public virtual Owner Owner { get; set; }
}
public class Owner
{
// Properties
public Guid Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public DateTime SignupDate { get; set; }
// Navigation
public virtual ICollection<Dog> Dogs { get; set; }
}
我还设置了我的 Dog 控制器来处理查询:
public class DogsController : ODataController
{
DogHotelAPIContext db = new DogHotelAPIContext();
#region Public methods
[Queryable(AllowedQueryOptions = System.Web.Http.OData.Query.AllowedQueryOptions.All)]
public IQueryable<Dog> Get()
{
var result = db.Dogs.AsQueryable();
return result;
}
[Queryable(AllowedQueryOptions = System.Web.Http.OData.Query.AllowedQueryOptions.All)]
public SingleResult<Dog> Get([FromODataUri] Guid key)
{
IQueryable<Dog> result = db.Dogs.Where(d => d.Id == key).AsQueryable().Include("Owner");
return SingleResult.Create(result);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
我已经在数据库中植入了一些示例数据。所有狗记录都有一个 OwnerId,它与 Owners 表中所有者的 ID 相匹配。
使用此方法查询狗列表效果很好:
http://localhost:49382/odata/Dogs
我得到一个 Dog 实体列表,没有 Owner 导航属性。
使用 OData $expand 与主人一起查询狗不起作用:
http://localhost:49382/odata/Dogs?$expand=Owner
我的响应是包含所有 Dog 实体的 200,但它们都没有 JSON 中的 Owner 属性。
如果我查询我的元数据,我发现 OData 似乎确实知道它:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="DogHotelAPI.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityType Name="Dog">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="Edm.Guid" Nullable="false" />
<Property Name="name" Type="Edm.String" />
<Property Name="breed" Type="DogHotelAPI.Models.Enums.DogBreed" Nullable="false" />
<Property Name="age" Type="Edm.Int32" Nullable="false" />
<Property Name="weight" Type="Edm.Int32" Nullable="false" />
<Property Name="ownerId" Type="Edm.Guid" />
<NavigationProperty Name="owner" Type="DogHotelAPI.Models.Owner">
<ReferentialConstraint Property="ownerId" ReferencedProperty="id" />
</NavigationProperty>
</EntityType>
<EntityType Name="Owner">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="Edm.Guid" Nullable="false" />
<Property Name="name" Type="Edm.String" />
<Property Name="address" Type="Edm.String" />
<Property Name="phone" Type="Edm.String" />
<Property Name="signupDate" Type="Edm.DateTimeOffset" Nullable="false" />
<NavigationProperty Name="dogs" Type="Collection(DogHotelAPI.Models.Dog)" />
</EntityType>
</Schema>
<Schema Namespace="DogHotelAPI.Models.Enums" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EnumType Name="DogBreed">
<Member Name="AfghanHound" Value="0" />
<Member Name="AmericanStaffordshireTerrier" Value="1" />
<Member Name="Boxer" Value="2" />
<Member Name="Chihuahua" Value="3" />
<Member Name="Dachsund" Value="4" />
<Member Name="GermanShepherd" Value="5" />
<Member Name="GoldenRetriever" Value="6" />
<Member Name="Greyhound" Value="7" />
<Member Name="ItalianGreyhound" Value="8" />
<Member Name="Labrador" Value="9" />
<Member Name="Pomeranian" Value="10" />
<Member Name="Poodle" Value="11" />
<Member Name="ToyPoodle" Value="12" />
<Member Name="ShihTzu" Value="13" />
<Member Name="YorkshireTerrier" Value="14" />
</EnumType>
</Schema>
<Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityContainer Name="Container">
<EntitySet Name="Dogs" EntityType="DogHotelAPI.Models.Dog">
<NavigationPropertyBinding Path="owner" Target="Owners" />
</EntitySet>
<EntitySet Name="Owners" EntityType="DogHotelAPI.Models.Owner">
<NavigationPropertyBinding Path="dogs" Target="Dogs" />
</EntitySet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
我可能遗漏了什么会阻止我的导航预操作与我的模型的其余部分一起返回?
编辑
为了进一步隔离问题,我尝试在服务器端包含 C# 中的 Owners。我在我的 Dog 控制器的 Get 方法中添加了这一行:
var test = db.Dogs.Include("Owner").ToList();
有了这个我可以调试并看到相关的所有者被包括在内。在此列表中,每只狗都有与之关联的主人。
对实际返回的内容使用 .Include("Owner") 并不能解决问题 - 属性仍然永远不会到达客户端。
这似乎意味着导航属性正在工作,但没有被发送回客户端。我猜这似乎表明 OData 或 WebAPI 存在问题,但我不确定是什么。
此外,我还在 Global.asax 文件中的 Application_Start 中添加了以下几行,以处理循环导航属性:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
我这样做是为了以防循环引用在某种程度上是罪魁祸首,但这没有任何改变。
更新
我注意到打电话给
http://localhost:49382/odata/Dogs(abfd26a5-14d8-4b14-adbe-0a0c0ef392a7)/owner
有效。这将检索与该狗关联的所有者。这进一步说明我的导航属性设置正确,它们只是没有包含在使用 $expand 的调用响应中。
更新 2
这里是我的WebApiConfig文件的注册方法:
public static void Register(HttpConfiguration config)
{
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();
builder.EntitySet<Dog>("Dogs");
builder.EntitySet<Owner>("Owners");
config.EnableQuerySupport();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: builder.GetEdmModel());
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
【问题讨论】:
-
在我自己的功能性 OData v4 设置上进行测试。我发现放置 include("RelatedEntity") 也没有返回相关实体。我试图研究如何在 $expand 命令被传递到 API 后对其进行调试,但无法找到该信息。我建议是否可以使用 Visual Studio 提供的 Scaffolding 来生成 Owner 和 Dog 控制器。调整您的 [Queryable] 以满足您对生成的通用的要求,并尽可能尝试这种方式。
-
我仍然认为它可能只是与导航属性和外键设置有关。也许可以尝试在带有断点的单独类中进行非 OData 查询,以查看是否可以提取两个数据点以验证是否使用通用实体查询设置了关系。
标签: c# entity-framework asp.net-web-api odata navigation-properties