use*_*986 4 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
代码背后
private List<ArtistServiceReference.Artist> ArtistDetail()
{
ArtistServiceReference.ArtistServiceClient client = new
ArtistServiceReference.ArtistServiceClient();
ArtistServiceReference.Artist[] artists = client.ArtistDetail();
return artists.ToList();
Run Code Online (Sandbox Code Playgroud)
我想将Artist List移动到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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
示例default.aspx.cs
private List<TaskService.Task> GetTasks()
{
TaskService.MyServiceClient client = new TaskService.MyServiceClient();
TaskService.Task[] tasks = client.GetTasks();
return tasks.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这个例子会起作用而不是我的.唯一的区别是这个例子是返回gridview,我想返回一个下拉列表.
Ser*_*kiy 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,看起来Artist你的ArtistsDbSet中有实体.为什么不简单地回来
return db.Artists.ToList();
Run Code Online (Sandbox Code Playgroud)