c# - 如何使用 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 格式显示:
我怎样才能做到这一点?
解决方案
我刚刚找到了我想要的答案:
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
}
最后,它与用户一起“运行”该行,(从数据库中检索所有用户并创建用户列表)并自动填充以前的列表,因此我从数据库中检索了所有信息。
推荐阅读
- php - 无法从 Intranet 读取图像,php 导出到 word
- java - sonarqube 6.7.2 构建失败 Java 并且无法在报告中存储文件源
- android - 在 DownloadManager DOWNLOAD_COMPLETE 广播接收器上接收广播 Intent 时出错
- vba - VBA Excel,比较单元格中的字符串
- hibernate - .save() 没有保存列表中给出的所有详细信息
- javascript - 使用js显示div中的元素列表
- sql - SQL - 需要在同一张表中为客户打印相同数量的记录和相同的产品
- javascript - viewer.js 在 IE 11 中的选项卡切换处触发 addEventListener 调整大小,导致错误和崩溃
- html - sp_notify_operator 的 T-SQL Server 代理格式化消息
- selenium - 在 Selenium 中处理 Windows 打开文件对话框