簡體   English   中英

基於可空主鍵列的實體框架分組

[英]Entity Framework Group by based on a Nullable Primary Key column

我用於存儲地址的實體如下所示,並將多個表稱為外鍵,例如國家/地區等

public class ContactAddress
{
    [Key]
    public int Id { get; set; }

    [ForeignKey(nameof(Contact))]
    public int ContactId { get; set; }

    public virtual  Contact Contact { get; set; } 
    
    [ForeignKey(nameof(Continent))]
    public int? ContinentId { get; set; }

    public virtual  Continent Continent { get; set; }

    [ForeignKey(nameof(Country))]
    public int? CountryId { get; set; }

    public virtual  Country Country { get; set; }
}

嘗試獲取國家和大陸的地址值計數以及 map 的結果到List<GeoStatsModel>就像

public class GeoStatsModel
{
    public int Id { get; set; } // Country Id
    public string Name { get; set; }  //Country Name
    public int Count { get; set; }
}           

設法生成如下查詢

 List<GeoStatsModel> response = new List<GeoStatsModel>();

 response = context.ContactAddresses
                   .Where(a => a.IsPrimary == true && contactIds.Contains(a.ContactId))
                   .GroupBy(a => a.CountryId) 
                   .Select(g => new GeoStatsModel 
                                    {
                                        Id = (int)g.Key, 
                                        Name = (g.First().Country!=null)? g.First().Country.Name: "",
                                        Count = g.Count() 
                                    }).ToList(); 

在執行時,我收到錯誤:

LINQ 表達式 'GroupByShaperExpression: KeySelector: (Nullable)c.CountryId, ElementSelector:EntityShaperExpression: EntityType: ContactAddress ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False

.Select(s => s.Country).First()' 無法翻譯。 以可翻譯的形式重寫查詢,或通過插入對“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的調用顯式切換到客戶端評估。 有關詳細信息,請參閱https://go.microsoft.com/fwlink/?linkid=2101038

我們如何正確地從外鍵表中返回名稱並對結果進行分組?

GroupBy支持在 EF 核心中受到限制。 它基本上支持 SQL 支持的語句,在 EF 核心 6 中更多一點。

在 SQL 中,不可能按CountryId分組,並且在結果集中也有國家名稱(至少不是在所有 RDBMS 中)。 要在 SQL 中執行此操作,該語句應與Country連接,然后按CountryIdCountry.Name分組。 這就是 EF 也支持的:

var response = context.ContactAddresses
    .Where(a => a.IsPrimary && contactIds.Contains(a.ContactId))
    .GroupBy(a => new { a.CountryId, a.Country.Name }) 
    .Select(g => new GeoStatsModel 
    {
        Id = g.Key.CountryId ?? 0, 
        Name = g.Key.Name ?? string.Empty,
        Count = g.Count() 
    }).ToList();

暫無
暫無

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

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