JSON创建中的问题。 [英] Problem in JSON Creation.
问题描述
我正在使用EF开发Web API控制器。当我像下面的代码一样使用单个表时正确获取JSON对象。
静态IEnumerable < ProductIdAndName > SelectTop5ProductsIdAndName()
{
NorthwindEntities northwindEntities = new NorthwindEntities();
string nativeSQLQuery =
SELECT TOP 5 ProductID as ID,ProductName as Name+
FROM dbo.Products+
ORDER BY ProductID;
ObjectResult < ProductIdAndName > products =
northwindEntities.ExecuteStoreQuery < ProductIdAndName > 跨度>(nativeSQLQuery);
退货产品;
}
当我使用两个表时,我写了如下,因为我从多个表中获取值。
静态IEnumerable < 对象 > SelectTop5ProductsIdAndName()
{
NorthwindEntities northwindEntities = new NorthwindEntities();
string nativeSQLQuery =
SELECT TOP 5 * FROM dbo.Products,dbo.ProductsPrice ORDER BY ProductID;
ObjectResult < 对象 > products =
northwindEntities.ExecuteStoreQuery < Object > 跨度>(nativeSQLQuery);
退货产品;
}
在这种情况下,我无法获得JSON,因为返回类型是对象。请给出建议来解决这个问题。
注意:我对创建视图模型不感兴趣。
很少我注意到的事情
1.使用EF并在线编写SQL查询很糟糕。您不必显式编写SQL查询
2.以下查询可能对您有用,但这不是一个好习惯。假如你真的想要使用多个表的sql查询,用户内/外连接
SELECT TOP 5 * FROM dbo.Products,dbo.ProductsPrice ORDER BY ProductID
来到解决方案。构建一个视图模型或类来保存两个表的结果。您应该获取并返回视图模型。
如果您有任何疑问,请告诉我。
谢谢,
I am working on Web API controllers with EF. When i use a single table like following code am getting the JSON object correctly.
static IEnumerable<ProductIdAndName> SelectTop5ProductsIdAndName()
{
NorthwindEntities northwindEntities = new NorthwindEntities();
string nativeSQLQuery =
"SELECT TOP 5 ProductID as ID, ProductName as Name " +
"FROM dbo.Products " +
"ORDER BY ProductID";
ObjectResult<ProductIdAndName> products =
northwindEntities.ExecuteStoreQuery<ProductIdAndName>(nativeSQLQuery);
return products;
}
When i use two tables i wrote like following because i am getting values from multiple tables.
static IEnumerable<Object> SelectTop5ProductsIdAndName()
{
NorthwindEntities northwindEntities = new NorthwindEntities();
string nativeSQLQuery =
"SELECT TOP 5 * FROM dbo.Products, dbo.ProductsPrice ORDER BY ProductID";
ObjectResult<Object> products =
northwindEntities.ExecuteStoreQuery<Object>(nativeSQLQuery);
return products;
}
In this case am not able to get the JSON, as the return type is of object. Please give suggestios to solve this.
Note: I am not interested in creating viewmodels.
Few things I noticed
1. Using EF and writing a SQL query inline is bad. You don't have to explicitly write sql queries
2. The following query might work for you but it's not a good practice. Say if you really want to use sql queries with multiple tables, user inner/outer joins
SELECT TOP 5 * FROM dbo.Products, dbo.ProductsPrice ORDER BY ProductID
Coming to the solution. Build a viewmodel or a class to hold the results of both tables. You should fetch and return the viewmodel.
Let me know if you have any doubts.
Thanks,
这篇关于JSON创建中的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!