不允许在查询中显式构造实体类型“Artist”

时间:2014-01-21 17:53:32

标签: c# linq entity-framework

编译得很好,但执行失败,标题中出现错误。

ArtistService.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();

我想将艺术家列表移动到DropdownList。

错误发生在最后的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,我想返回一个下拉列表。

1 个答案:

答案 0 :(得分:10)

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();
        }
    }
}

顺便说一下,您的Artist DbSet中有Artists个实体。为什么不简单地返回

 return db.Artists.ToList();