簡體   English   中英

不支持指定的方法MySql Entity Framwork 6

[英]Specified method is not supported MySql Entity Framwork 6

我正在嘗試從MySQL客戶端運行以下Linq查詢

    query = query.Where(c => c.CustomerRoles
                              .Select(cr => cr.Id)
                              .Intersect(customerRoleIds)
                              .Any()
                       );

這段代碼看起來還不錯,但給出了錯誤:

System.NotSupportedException: Specified method is not supported.at MySql.Data.Entity.SqlGenerator.Visit(DbIntersectExpression expression)

在我看來,這就像.Intersect的問題。 誰能告訴我這個錯誤的原因以及如何解決?

我認為@GertArnold的帖子是正確且最佳的答案,但我想知道為什么您還收到NotSupportedException 因此問題可能不應該來自intersect

customerRoleIds來自哪里? IQueryable<T>嗎?

中斷查詢,並逐步完成查詢。

如果您在以下行沒有遇到異常:

var a = query.Select(c => new { 
        c, 
        CustomerRoleIDList = c.CustomerRoles.Select(cr => cr.Id).AsEnumerable()
    })
    .ToList();

var b = customerRoleIds.ToList();

您必須通過以下方式獲得結果:

var b = query.Where(c => c.CustomerRoles.any(u => customerRoleIds.Contains(u.Id)))
    .ToList();

如果通過上述查詢獲得異常,則可以嘗試以下最終解決方案首先獲取數據,但是請注意,所有數據將首先在內存中獲取:

var a = query.Select(c => new { 
        c, 
        CustomerRoleIDList = c.CustomerRoles.Select(cr => cr.Id).AsEnumerable() 
    })
    .ToList();

var b = a.Where(c => c.CustomerRoleIDList.any(u => customerRoleIds.Contains(u)))
    .Select(u => u.c)
    .ToList();

對於LINQ到SQL后端,使用IntersectExcept可能總是很麻煩。 使用Sql Server,它們可能會產生可怕的SQL查詢。

通常會支持Contains因為它可以輕松轉換為SQL IN語句。 您的查詢可以改寫為

query = query.Where(c => c.CustomerRoles
                 .Any(cr => customerRoleIds.Contains(cr.Id)));

我認為customerRoleIds不會包含很多項(通常不會有數百個角色),否則您應注意不要達到IN語句中允許最大項數

嘗試在相交之前添加toList(),它應該在本地枚舉結果,而不是在MySql上運行,這樣會導致性能下降。

 query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id)).ToList().Intersect(customerRoleIds);
query.Where(c => c.CustomerRoles
                 .Any(v=>customerRoleIds.Any(e=>e == v.Id))
     .Select(cr => cr.Id))
     .ToList();

暫無
暫無

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

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