我的问题是使用"子数据模型填充数据模型" 在这种情况下,我有很多产品。每种产品都有分类,但有些产品根本没有分类。产品甚至可以链接到几个类别。不知道我应该怎么做。 这是我到目前为止所得到的:
数据库,表结构:
tProduct
ProductId int
ProductName varchar(250)
tCategory
CategoryId int
CategoryName varchar(250)
tLinkProductCategory
ProductId int
CategoryId int
数据模型:
public class ProductModel
{
public int ProductId;
public string ProductName
public IEnumerable<CategoryModel> Categories;
}
public class CategoryModel
{
public int CategoryId;
public string CategoryName;
}
查询:
public IQueryable<ProductModel> GetProductQuery()
{
var query = from product in DataContext.tProduct
//left join
from linkProductCategory in DataContext.tLinkProductCategory.Where(e => e.ProductId == product.ProductId).DefaultIfEmpty()
//left join
from category in DataContext.tCategory.Where(e => e.CategoryId == linkProductCategory.CategoryId).DefaultIfEmpty()
select new ProductModel() {
ProductName = product.Name
Categories = //something missing here
};
return query;
}
更新 这种方法起到了作用:
..
select new ProductModel() {
ProductName = product.ProductName,
Categories = product.tLinkProductCategory.Select(c => new CategoryModel
{
CategoryID = c.tCategory.CategoryId,
CategoryName = c.tCategory.CategoryName
}
}
...
答案 0 :(得分:1)
尝试此查询:
from product in DataContext.tProduct
select new ProductModel()
{
ProductName = product.ProductName,
Categories = (from category in DataContext.tCategory
join linkProductCategory in DataContext.tLinkProductCategory on category.CategoryId equals linkProductCategory.CategoryId
where linkProductCategory.ProductId == product.ProductId
select category
).ToList()
};