[英]Why cant we select any properties on the many side when we are using .Select(x=>new object) on Linq
i just wonder about something which has no sense to me.我只是想知道一些对我来说毫无意义的事情。 I'm using ASP.NET Core 5.0 and im using Linq.
我使用的是 ASP.NET Core 5.0,我使用的是 Linq。
I have a to class which has relationship One (MainCategory) - To - (Category) Many
.我有一个 to 类,它有关系
One (MainCategory) - To - (Category) Many
。 I wanna write a linq which is gonna targeting to get MainCategoryName
and CategoryID
.我想写一个 linq,它的目标是获取
MainCategoryName
和CategoryID
。 Let me show to you my linq :让我向你展示我的 linq :
public IEnumerable<MainCategory> GetMainCategoryForFair()
{
return DBContext.MainCategories.Where(x => x.MainCategoryIsFeatured == true
&& x.IsDeleted != true)
.Select(x => new MainCategory
{
MainCategoryName = x.MainCategoryName,
Categories = x.Categories
}).ToList();
}
I know, that query gonna take all properties of Categories
and this is the thing im trying to avoid.我知道,该查询将采用
Categories
所有属性,这是我试图避免的事情。 Is it possible ?是否有可能 ?
if it's possible,then how ?如果可能,那么如何?
if it's not, why ?如果不是,为什么?
Sure.当然。 Just don't project all the properties.
只是不要投影所有属性。 And normally if you are returning a different data shape, you would introduce a new class to return, instead of returning an Entity type with a bunch of null properties, eg
通常如果你要返回一个不同的数据形状,你会引入一个新的类来返回,而不是返回一个带有一堆空属性的实体类型,例如
public IEnumerable<MainCategoryDTO> GetMainCategoryForFair()
{
return DBContext.MainCategories.Where(x => x.MainCategoryIsFeatured == true
&& x.IsDeleted != true)
.Select(x => new MainCategoryDTO()
{
MainCategoryName = x.MainCategoryName,
Categories = x.Categories.Select( c => new CategoryDTO(){CategoryName = c.Name, ...}).ToList()
}).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.