【发布时间】:2015-07-08 23:43:48
【问题描述】:
我正在使用 Web API 5、OData 和 Entity Framework 6 开发一个 ASP.Net MVC5 应用程序。我创建了存储库并使用 Entity Framework Power Tools 来生成我的实体模型。我已经在我的 DBContext 上关闭了延迟加载和代理生成。下面是我如何在存储库类中编写 LINQ 查询以返回具有关系的实体;
return repository
.Query(i => i.IsTransaction == true)
.Include(i => i.SubInventory)
.Include(c => c.Contact)
.OrderBy(q => q
.OrderBy(i => i.ItemFullCode))
.Select();
在我设置的 ODataConfig 文件中进一步;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.Objects;
我正在努力解决的问题是我的 Web API 方法 JSON 响应不包含 LINQ 查询中包含的关系,而只是主要实体数据。知道我在这里缺少什么吗?
以下是我的主要实体的代码。
public partial class Item : Entity
{
public Item()
{
this.DocumentDatas = new List<DocumentData>();
this.ItemColorSizes = new List<ItemColorSize>();
this.ItemPrices = new List<ItemPrice>();
this.Items1 = new List<Item>();
this.ItemStocks = new List<ItemStock>();
this.SeasonalSaleDetails = new List<SeasonalSaleDetail>();
}
public string ItemFullCode { get; set; }
public string ItemCode { get; set; }
public string ItemName { get; set; }
public string ItemShortCode { get; set; }
public string LevelItemFullCode { get; set; }
public string SupplierCode { get; set; }
public string SubInvCode { get; set; }
public Nullable<decimal> PurchasePrice { get; set; }
public Nullable<decimal> SalePrice { get; set; }
public Nullable<System.DateTime> ArrivalDate { get; set; }
public string RefCode { get; set; }
public Nullable<decimal> TColumn { get; set; }
public Nullable<bool> TColumnByAmt { get; set; }
public Nullable<bool> IsGiftItem { get; set; }
public Nullable<bool> IsTransaction { get; set; }
public Nullable<bool> IsActive { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Contact Contact { get; set; }
public ICollection<DocumentData> DocumentDatas { get; set; }
public ICollection<ItemColorSize> ItemColorSizes { get; set; }
public ICollection<ItemPrice> ItemPrices { get; set; }
public ICollection<Item> Items1 { get; set; }
public Item Item1 { get; set; }
public SubInventory SubInventory { get; set; }
public ICollection<ItemStock> ItemStocks { get; set; }
public ICollection<SeasonalSaleDetail> SeasonalSaleDetails { get; set; }
}
【问题讨论】:
-
你能告诉我们
repository的定义是什么样的吗?您还可以确认在代码中,当您在返回后设置断点时,所有预期的相关对象都已被反序列化。我怀疑该功能不适用于实体关系。我的经验是,如果你有一个递归结构,你就需要它。就像引用相同类型数组的类型一样。 -
您是先使用代码吗?你能展示你的实体吗?
-
@evanmcdonnal 我使用了下面链接中解释的架构blog.longle.net/2013/05/11/… 我设置了一个断点,甚至序列化了存储库中包含所有相关对象的返回对象。只有在客户端我没有收到由所有对象组成的 JSON。
-
@TheVedge 我已经使用 Entity Framework Power Tools 对我的实体进行了逆向工程。
标签: c# json linq entity-framework