簡體   English   中英

不允許在查詢中顯式構造實體類型“藝術家”

[英]Explicit construction of entity type 'Artist' in query is not allowed

編譯很好,但執行失敗,標題中出現錯誤。

藝術家服務.cs

public class ArtistService : IArtistService
{
    public List<Artist>  ArtistDetail()  
    {
        using (ArtistDataContext db = new ArtistDataContext())
        {
            return (from artist in db.Artists

                select new Artist()
                {
                    Id = artist.Id,
                    Artist_name = Artist.Artist_name
                }).ToList();     <=== error happened here
        }
    }
}

背后的代碼

private List<ArtistServiceReference.Artist> ArtistDetail()
{
    ArtistServiceReference.ArtistServiceClient client = new 
    ArtistServiceReference.ArtistServiceClient();

    ArtistServiceReference.Artist[] artists = client.ArtistDetail();

    return artists.ToList();

我想將藝術家列表移動到下拉列表。

錯誤發生在 ArtistService.cs 末尾 {).ToList(); 有關如何解決此問題的任何解釋? 謝謝

我的代碼基於此示例,並且此示例運行良好。

示例代碼 MyService.cs

public class MyService : IMyService
{
    public List<Task> GetTasks()
    {
        using (TasksDataContext db = new TasksDataContext())
        {
            return (from task in db.TasksLists
                select new Task()
                {
                    Id = task.taskId,
                    Name = task.taskName,

                }).ToList();
        }
    }
}

示例 default.aspx.cs

private List<TaskService.Task> GetTasks()
{
    TaskService.MyServiceClient client = new TaskService.MyServiceClient();

    TaskService.Task[] tasks = client.GetTasks();

    return tasks.ToList();
}

我不明白為什么這個例子會起作用而不是我的。 唯一的區別是此示例返回到 gridview,而我想返回到下拉列表。

Linq to Entities 無法將 Artist 對象的創建轉換為 SQL 代碼(真的,這應該是什么樣子的?)。 Linq to Entities 只能執行 SQL 查詢並將返回的字段映射到它知道如何映射到的某個實體(即您的 DbSet 實體)。 因此,您需要先執行查詢,然后在本地創建 Artist 實體:

public class ArtistService : IArtistService
{
    public List<Artist>  ArtistDetail()  
    {
        using (ArtistDataContext db = new ArtistDataContext())
        {
            return (from artist in db.Artists
                    select new { // select only columns you need
                       artist.Id,
                       artist.Artist_name
                    })
                    .AsEnumerable() // execute query
                    .Select(x => new Artist { // create instance of class
                        Id = x.Id,
                        Artist_name = x.Artist_name
                    })
                    .ToList();
        }
    }
}

順便說一句,您的Artists DbSet 中似乎有Artist實體。 為什么不簡單地返回

 return db.Artists.ToList();

暫無
暫無

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

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