C#Linq不能按照JSON结果所需的顺序格式化输出列表

时间:2015-01-23 19:15:31

标签: 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; }
    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; }
}

我的控制器

        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"}}]

所以问题是我得到的错误有时是循环错误或LINQ

  

LINQ to Entities无法识别方法&#39; System.Collections.Generic.Dictionary`2 [System.Guid,System.Double] ToDictionary [DeliveryCost,Guid,Double]

1 个答案:

答案 0 :(得分:0)

问题是LINQ to Entities无法将表达式转换为SQL。并非每个C#表达式树都可以转换为SQL,只支持一组有限的操作。

你总是可以通过在内存中实现实体并在内存中进行转换来解决这类问题。因此,在数据库中查询所需的实体,并使用.ToList()将它们拉入内存,然后对它们进行处理,将它们整形为所需的JSON。

这是否有效取决于具体情况。它可能效率较低,或者它实际上比在SQL中执行等效工作更有效。你所能做的只是试一试,看看。

相关问题