c# - 如何使用 linq to entities 获取字符串数组或 JSON 格式的数据?

标签 c# asp.net json entity-framework linq

我有一个 ASP.Net MVC5 站点并使用 EF 6.0

一对多关系

这是我的模型

public class Singer
{
    [Key]
    public int SingerID { get; set; }

    public string SingerName { get; set; }

    public virtual List<Album> Albums { get; set; }
}

public class Album
{
    [Key]
    public int AlbumID { get; set; }

    public string AlbumName { get; set; }

    public string AlbumDate { get; set; }

    [ForeignKey("Singer")]
    public int SingerID { get; set; }

    public virtual Singer Singer { get; set; }
}

现在我的 Linq 如下所示

public IEnumerable<T> GetAlbums()
{
    using (dbContext db = new dbContext())
    {
        IQueryable<T> query = (from c in db.Albums
                               group c.AlbumId by c.SingerId into albums
                               select new AlbumMapper()
                               {
                                   AlbumID = albums.Key,
                                   Total = albums.Count()
                               })
        }
}

在当前场景中,我获取了按 albumId 和专辑数量分组的所有专辑。

但我的需要是形成如下所示的 JSON 字符串

[
   {
      "SingerID":1,
      "Albums":[
         {
            "AlbumName":"This is Album 1",
            "AlbumDate":"Dec 30,2015"
         },
         {
            "AlbumName":"This is Album 2",
            "AlbumDate":"Dec 30 2015"
         }
      ]
   },
   {
      "SingerID":2,
      "Albums":[
         {
            "AlbumName":"This is Album 1",
            "AlbumDate":"Dec 30,2015"
         },
         {
            "AlbumName":"This is Album 2",
            "AlbumDate":"Dec 30 2015"
         }
      ]
   }
]

添加映射器类

public class AlbumDetails
{
   public DateTIme AlbumDate

   public string AlbumName

}

public class AlbumMapper
{
    public int AlbumID

    public IEnumerable<AlbumDetails> Albums  
}

最佳答案

只需将所有歌手放入列表并使用 Json.NET ( http://www.newtonsoft.com/json ) 将其序列化

如果您想省略 SingerName,请务必向属性添加 [JsonIgnore] 数据属性

关于c# - 如何使用 linq to entities 获取字符串数组或 JSON 格式的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34530956/

相关文章:

c# - WebClient CookieContainer 在 .NET 4.0+ 中运行良好,但在早期版本中运行不佳

c# - 使用接口(interface)如何克服C#中的多重继承问题?

ASP.net View 状态和端口

asp.net - 脚本控件可能不会在 PreRender 之前注册。使用定时器控制时

php - 在 PHP 中通过 JSON API 获取 Youtube 订阅者数量

c# - 创建一个带有命名空间的 xml 文件

asp.net - 我可以在 IIS 中自动创建 .NET Web 应用程序吗?

android - 在另一个 JSON 对象中访问一个 JSON 对象

json - laravel验证Content-Type : application/json request

c# - Cookie 和 C# HttpWebRequest