【发布时间】:2015-01-19 11:26:57
【问题描述】:
我正在尝试在 ASP Web API 中创建以下输出:
User[]
--> Category[]
--> Transaction[]
所以我有很多用户有几个类别和很多与该类别相关的交易。 这似乎很容易,但由于以下问题,我无法让它工作: 我的数据库模型如下:
//Transaction
TransactionID
Quantity
CategoryID
UserID
//Category
ID
Name
//User
ID
Name
问题是返回一个 json/xml 响应,例如:
User1
--Cate1
----Tran1
----Tran2
--Cate2
----Tran3
User2
--Cate1
----Tran4
因为仅通过事务在用户和类别之间没有单独的链接,我不知道如何通过 LINQ 查询或其他方式解决此问题。
--编辑 我的控制器代码:
List<User> Users = new List<User> {
new User {Id = 1, Name = "Matt" },
new User {Id = 2, Name = "Bill" },
new User {Id = 3, Name = "Peter" },
new User {Id = 4, Name = "Bart" }
};
List<Category> Categories = new List<Category> {
new Category {Id = 1, Name = "Sales" },
new Category {Id = 2, Name = "After Sales" },
new Category {Id = 3, Name = "Pre Sales" }
};
List<Transaction> Transactions = new List<Transaction> {
new Transaction {Id = 1, Quantity = 200, CategoryId = 1 , UserId = 1},
new Transaction {Id = 2, Quantity = 150, CategoryId = 2 , UserId = 1 },
new Transaction {Id = 3, Quantity = 300, CategoryId = 2 , UserId = 1 },
new Transaction {Id = 4, Quantity = 100, CategoryId = 1 , UserId = 2},
new Transaction {Id = 5, Quantity = 150, CategoryId = 2 , UserId = 2 },
new Transaction {Id = 6, Quantity = 250, CategoryId = 3 , UserId = 3 },
new Transaction {Id = 7, Quantity = 200, CategoryId = 1 , UserId = 4},
new Transaction {Id = 8, Quantity = 50, CategoryId = 2 , UserId = 4 },
new Transaction {Id = 9, Quantity = 250, CategoryId = 3 , UserId = 4 }
};
//(new int[] { 2, 3, 5 });
public List<UserDTO> Get()
{
var User = from d in Users
select new UserDTO
{
User = d,
/* Here I have the Problem
* I can't link the categories to the users without calling all transactions
* And then the result will for UserId = 1 will return 3 categories but 2 times After Sales and I want to return it onces
*/
Categories = (from c in Transactions
where c.UserId == d.Id
select new CategoryDTO
{
Category = c.Category,
Transactions = (from t in Transactions
where t.CategoryId == c.CategoryId && t.UserId == c.UserId
select new TransactionDTO
{
Id = t.Id,
Quantity = t.Quantity
}).ToList()
}).ToList()
};
return User.ToList();
}
所有 DTO 类:
public class UserDTO
{
public User User { get; set; }
public List<CategoryDTO> Categories { get; set; }
}
public class CategoryDTO
{
public Category Category { get; set; }
public List<TransactionDTO> Transactions { get; set; }
}
public class TransactionDTO
{
public int Id { get; set; }
public int Quantity { get; set; }
}
谢谢
【问题讨论】:
-
我一头雾水,你说要将数据输出为
User -> Category -> Transaction,然后抱怨这是你得到的输出类型... -
不,最后的例子是我想要的结果。只是一个更详细的
-
但是您已经在那里建立了关系,向我们展示您目前在做什么以及为什么它没有给您想要的输出。
-
首先获取可查询的事务,然后按用户分组,然后按类别。在高层次返回一个新用户,在中层次返回一个新类别。最后一级返回您的交易。你需要创建自己的 DTO 类来做到这一点
-
听起来你的数据结构实际上是对交易进行分类而不是对用户进行分类。用户属于类别,还是属于事务?我的建议是先构建一个 SQL 查询,看看能不能得到你想要的结果,然后翻译成 Linq。
标签: c# linq asp.net-web-api2