【发布时间】:2020-04-27 16:45:14
【问题描述】:
这是我的数据结构:
public class Product
{
// Rest of props
public ICollection<ProductUpdate> ProductUpdate { get; set; }
}
public class ProductUpdate
{
// Rest of props
public Delivery Delivery { get; set; }
}
public class Delivery
{
// Rest of props
public virtual ICollection<DeliveryUsersApprovers> DeliveryUsersApprovers { get; set; }
}
public class DeliveryUsersApprovers
{
// Rest of props
public User User { get; set; }
}
我如何编写一个 linq 方法语法查询,该查询将从 ProductUpdate 中选择 Id、StartDate 和 Note,同时它会为每一行选择 ProductUpdate 对应的用户进行更新,其中包含DeliveryUsersApprovers 班级..
我想使用.Select() 来实现它以仅获取所需的列..
我已经尝试过类似的方法,但它不起作用:
var paymentStatusUpdates = await _dbContext.Product.Include(x => x.ProductUpdate)
.Select(x => new SomeCustomClassObjectWithFourProperties
{
// Read data from ProductUpdate somehow and select Id, Date and Note from ProductUpdate and get User from nested property
.Select(y=> new SomeCustomClassObjectWithFourProperties
{
Id = y.Id,
Date=y.StartDate,
Note=y.Note,
User=? // this is User from very nested prop
})
})
.FirstOrDefaultAsync(x => x.Id == productId, cancellationToken); //productId is received in method params
我真的很难深入了解嵌套道具并为每个 ProductUpdate 到达 User,所以任何形式的帮助都会很棒!!
谢谢
【问题讨论】:
-
您可以使用
SelectMany进行嵌套集合,但我不确定如何将这个查询翻译成sql -
@PavelAnikhouski 我不知道怎么做,我真的是这里的初学者
-
如果我没记错的话,
Deliveries属性不会是一个集合吗? -
@NamLe 不是收藏,我重命名为 Delivery
-
所以因为 1
ProductUpdate可能有 1Delivery,1Delivery可能有很多DeliveryUsersApprovers,1DeliveryUsersApprovers可能有 1User,我得出结论是 1ProductUpdate可能有很多User,对吗?
标签: c# linq linq-to-sql linq-to-entities entity