簡體   English   中英

無法使用實體框架從linq查詢轉換列表

[英]Cannot convert List from linq query using Entity Framework

我的程序中出現轉換錯誤。 我使用一種方法(使用Entity Framework)查詢db並獲取表Web_Groups_joint_Profils所有條目:

public partial class Web_Group_joint_Profils
{
    [Key]
    [Column(Order = 0)]
    [StringLength(255)]
    public string GroupName { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IDProfil { get; set; }
}

這是獲取所有行的方法:

public List<Web_Group_joint_Profils> GetGroupAndId()
{
    var grpId = context.WebGroupProfil
               .Select(a => new 
               {
                   GroupName = a.GroupName,
                   IDProfil = a.IDProfil
               }).ToList();
    return grpId;
 }

但是grpId無效:

無法將類型“ System.Collections.Generic.List <>隱式轉換為System.Collections.Generic.List”

當我將鼠標懸停在聲明ToList()它說

Creates a List<T> of an IEnumerable<out T>

所以我嘗試更改返回類型

List<IEnumerable<T>> 

沒有成功。 我猜我的linq查詢創建了一個我不知道如何處理的匿名類型。

該方法的類型為List<Web_Group_joint_Profils>但是您將返回匿名類型的List。 您可以這樣更改:

.Select(a => new Web_Group_joint_Profils
{
    GroupName = a.GroupName,
    IDProfil = a.IDProfil
}).ToList();

如果仍然出現錯誤,可能是因為您無法投影到映射的實體上,那么您需要從Web_Group_joint_Profils實體中創建具有所需屬性的DTO類,如下所示:

public class TestDTO
{
    public string GroupName { get; set; }
    public string IDProfil { get; set; }
}

然后:

.Select(a => new TestDTO
{
    GroupName = a.GroupName,
    IDProfil = a.IDProfil
}).ToList();

.Select()創建一個匿名類型的對象,因此列表必然是相同的匿名類型。 這與您返回的類型不同。

您需要.Select()進行的操作是創建所需類型的對象。 但是,Entity Framework不會喜歡它,因為它將嘗試將其轉換為它無法轉換的SQL。

因此,您的代碼可能需要像這樣:

public List<Web_Group_joint_Profils> GetGroupAndId()
{
    var grpId = context.WebGroupProfil
        .Select(a => new 
        {
            GroupName = a.GroupName,
            IDProfil = a.IDProfil
        })
        .AsEnumerable() // This forces EF to run the query and materialise the data as anon objects
        .Select(a=>new Web_Group_joint_Profils(a.GroupName, a.IDProfil)
        .ToList();
    return grpId;
}

我假設Web_Group_joint_Profils具有一個接受兩個參數的構造函數。 如果不是,只需修改構造以適合您的方案。

無需創建匿名對象列表,而是在LINQ select對象初始化程序中創建所需的對象:

.Select(a => new Web_Group_joint_Profils
{

暫無
暫無

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

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