簡體   English   中英

為什么我不能從 linq 語句中的 select 中刪除列/道具

[英]Why can't I remove columns/props from select in linq statement

我想刪除不需要顯示的列!

基本上客戶只需要看到FirstNameLastName ,所以我只想將FirstNameLastName返回給最終用戶。

但是如果我從選擇中刪除其他道具,我的應用程序就會中斷:

  var product = await _context.Products.OrderBy(p => p.CreatedDate)
                .Select(x => new Product
                {
                    ProductId = x.ProductId,
                    GroupId = x.GroupId,
                    ProductStatus = x.ProductStatus,
                    Title = x.Title,
                    Price = x.Price
                }).FirstOrDefaultAsync(u => u.ProductId == dbObj.Id && u.GroupId == ProductGroup.Drinks && u.ProductStatus.Id == (int)ProductStatusEnum.Active);

我想要這樣的東西:

  var product = await _context.Products.OrderBy(p => p.CreatedDate)
                .Select(x => new Product
                {
                    Title = x.Title,
                    Price = x.Price
                }).FirstOrDefaultAsync(u => u.ProductId == dbObj.Id && u.GroupId == ProductGroup.Drinks && u.ProductStatus.Id == (int)ProductStatusEnum.Active);

在經典的(T-SQL)SQL 語句中,我應該能夠在 WHERE 中有列,但在SELECT也沒有列,而在LINQ中,如果我在WHERE使用它們,我似乎必須在SELECT有列。

謝謝

干杯

您的查詢不是選擇列,而是選擇您正在設置屬性值的新Product對象。 在第二種情況下,您只設置了TitlePrice屬性,其他的都是默認值。

您可能想查看匿名類型,例如:

.Select(x => new { Title = x.Title, Price = x.Price });

只需更改 Linq 語句的順序即可。 首先在調用Select之前使用Where進行過濾,並使用匿名對象投射到:

var product = await _context.Products
                 .Where(u => u.ProductId == dbObj.Id 
                          && u.GroupId == ProductGroup.Drinks 
                          && u.ProductStatus.Id == (int) ProductStatusEnum.Active)
                 .OrderBy(p => p.CreatedDate)
                 .Select(x => new
                 {
                     Title = x.Title,
                     Price = x.Price
                 }).FirstOrDefaultAsync();

這將創建一個具有 2 個屬性TitlePrice的匿名類型( product )。


如果您不想使用匿名類型,另一種選擇是創建一個僅包含您想要的屬性的類。

public class ProductSummary
{
    public string Title { get; set; }
    public decimal Price { get; set; }                
}

然后你可以選擇進入具體的類:

 .Select(x => new ProductSummary { Title = x.Title, Price = x.Price })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM