首页 > 解决方案 > 如何使用 C# 代码检索另一个对象内部的对象的所有属性?

问题描述

我在 SQL Server 中有这三个表:

Evaluations (id, textreview, stars, userId, BookId)    
Books      (id, title, ..., userId)    
Users      (id, name, ...)

我有这段代码可以从我的表中获取数据:

public List<Evaluations> GetAllEvaluationsPerBook()
{
    string sqlCommand = "SELECT DISTINCT b.Title,ev.TextReview,ev.Stars, b.Id " +
                        "FROM[Services.BookDbContext].[dbo].[Evaluations] as ev, " +
                            "[Services.BookDbContext].[dbo].Books as b " +
                        "WHERE b.Id = ev.Book_Id";

    using (var context = new BookDbContext())
    {
        var evaluation = context.Evaluation.SqlQuery(sqlCommand).ToList();

        return evaluation;
    }
}

现在我正在使用 EF6 在 C# 中创建一个 WebApi 项目。我将动作与 HttpPost 一起使用。在其中一个中,我需要从数据库中检索一些对象并将它们以 json 格式发送到客户端,例如 Fiddler。更具体地说,我想获得书名以及所有评价。

现在我需要使用上面的代码创建下面的 json:

{"id":1, "textReview":"Good", "stars":3, "book":null, "user":null},    
{"id":2, "textReview":"Awfull", "stars":1, "book":null, "user":null},    
{"id":1, "textReview":"Good", "stars":3, "book":null, "user":null},    
{"id":4, "textReview":"非常好","stars":4, "book":null, "user":null}

EG:您可以在下面看到我从 DB 收到的结果,但我无法使其以 json 格式显示:

https://i.stack.imgur.com/dky9c.png

我怎样才能做到这一点?

标签: c#sql-serverasp.net-web-apientity-framework-6asp.net-web-api-routing

解决方案


我刚刚找到了我想要的答案:

public List<Evaluations> GetAllEvaluationsPerBook()
    {
        using (var context = new BookDbContext())
        {
            var evaluations = context.Evaluation.ToList();
            var books = context.Book.ToList();
            var users = context.User.ToList();

            return evaluations;
        }
    }

所以代码总是一行一行地运行。
变量评估创建一个列表,填充它自己的所有属性,除了保持为空的 Book 和 User 对象:

{  
   "id":1,
   "textReview":"The Book is good.",
   "stars":3,
   "book":null,
   "user":null
}

在“运行”下一行之后,它会填满书籍列表。但它也用新的书籍列表填充了之前的评估列表:

{  
   "id":1,
   "textReview":"The Book is good.",
   "stars":3,
   "book":{  
      "isbn":1,
      "title":"The Tomb",
      "author":"H. P. Lovecraft",
      "user":null
   },
   "user":null
}

最后,它与用户一起“运行”该行,(从数据库中检索所有用户并创建用户列表)并自动填充以前的列表,因此我从数据库中检索了所有信息。


推荐阅读