C#Linq can';按JSON结果所需的顺序格式化输出列表
我在格式化对象以序列化Json时遇到问题 我的模型:C#Linq can';按JSON结果所需的顺序格式化输出列表,c#,asp.net-mvc,json,linq,C#,Asp.net Mvc,Json,Linq,我在格式化对象以序列化Json时遇到问题 我的模型: [Table("Stores")] public class DeliveryPoint { [Key] public Guid StoreId { get; set; } [Required] [StringLength(20)] [Display(Name = "Store name")] public string StoreName { get; set; } publi
[Table("Stores")]
public class DeliveryPoint
{
[Key]
public Guid StoreId { get; set; }
[Required]
[StringLength(20)]
[Display(Name = "Store name")]
public string StoreName { get; set; }
public ICollection<Location> Location { get; set; }
public virtual Company Company { get; set; }
public List<DeliveryCost> DeliveryPrice{ get; set; }
}
[Table("Drop_Prices")]
public class DeliveryCost
{
[Key]
public Int16 id { get; set; }
public virtual DeliveryPoint Store { get; set; }
public virtual Location DC { get; set; }
public double Cost { get; set; }
}
所以问题是我得到的误差有时是圆误差或LINQ
LINQ to Entities无法识别方法'System.Collections.Generic.Dictionary'2[System.Guid,System.Double]到字典[DeliveryCost,Guid,Double]
问题是LINQtoEntities无法将表达式转换为SQL。并不是每个C#表达式树都可以转换为SQL,只支持有限的一组操作 通过在内存中具体化实体并在内存中进行转换,您始终可以绕过此类问题。因此,在数据库中查询所需的实体,并使用
.ToList()
将它们拉入内存,然后对它们进行处理,将它们塑造成所需的JSON
这是否有效在很大程度上取决于具体情况。它可能效率较低,或者实际上可能比在SQL中执行同等的工作效率更高。您所能做的就是尝试一下并查看。谢谢您的回答,但是我得到
在使用.ToList()序列化类型为
的对象时检测到循环引用,这是不同的错误消息吗?问题中的一个是“LINQ to实体不识别该方法…”?您是否收到两条不同的错误消息?如果您遇到这种错误,它表明模型或数据有问题,但从代码中很难区分。我仍然想先用一种简单的方式具体化实体,然后在内存中处理它们。无论如何,它可能更快。不,当我尝试使用.ToList()时,会出现另一个错误,可能是因为我的模型设置不好或其他原因。这可能是因为以下行:d.DeliveryPrice.ToDictionary(item=>item.DC.LocationID,item=>item.Cost),您是否检查了此帖子:
public JsonResult GetAllStores()
{
var stores = _db.Stores.Select(d => new MyClass
{
name = d.StoreName,
cost = d.DeliveryPrice.ToDictionary( item => item.DC.LocationID,item=> item.Cost)
}).ToList();
return Json(stores, JsonRequestBehavior.AllowGet);
}
public class MyClass
{
public string name { get; set; }
public Dictionary<Guid,double> cost { get; set; }
}
[{"name":"foo","cost":{"82ec8689-d9e3-49e6-ba12-af091ac42760":"400"}}]