我在GridView1.DataBind();
中收到此错误不允许在查询中明确构造实体类型“WebApplication1.MUser”。
using (var db = new UsersDataContext())
{
IEnumerable<MUser> user = from u in db.MUsers
where u.Id == 1
select new MUser {Username = u.Username, Id = u.Id, Password=u.Password, ProjectUsers=u.ProjectUsers };
GridView1.DataSource = user;
GridView1.DataBind();
}
如何解决这个问题?
我正在学习本教程 http://weblogs.asp.net/scottgu/archive/2007/04/21/new-orcas-language-feature-query-syntax.aspx
答案 0 :(得分:2)
如果您关心性能,则应将查询更改为:
using (var db = new UsersDataContext())
{
IEnumerable<MUser> user = from x in
(from u in db.MUsers
where u.Id == 1
select u).AsEnumerable()
select new MUser { Username = x.Username, Id = x.Id, Password = x.Password, ProjectUsers = x.ProjectUsers };
GridView1.DataSource = user;
GridView1.DataBind();
}
答案 1 :(得分:1)
但匿名类型无法在WCF中进行序列化。
答案 2 :(得分:0)
如果您想要返回完整的Muser对象,请使用:
using (var db = new UsersDataContext())
{
IEnumerable<MUser> user = from u in db.MUsers
where u.Id == 1
select u;
GridView1.DataSource = user;
GridView1.DataBind();
}
或者,如果要返回用户的自定义部分(即只有Muser对象中的某些属性),可以使用匿名类型,如下所示。
using (var db = new UsersDataContext())
{
IEnumerable<MUser> user = from u in db.MUsers
where u.Id == 1
select new {Username = u.Username, Id = u.Id, Password=u.Password, ProjectUsers=u.ProjectUsers };
GridView1.DataSource = user;
GridView1.DataBind();
}
答案 3 :(得分:0)
您无法在查询中构造实体类型。 MS认为开发人员太愚蠢,会混淆自己(除其他外)。一个快速,简单,低效的解决方案......
using (var db = new UsersDataContext())
{
IEnumerable<MUser> user = from u in db.MUsers.AsEnumerable()
where u.Id == 1
select new MUser {Username = u.Username, Id = u.Id, Password=u.Password, ProjectUsers=u.ProjectUsers };
GridView1.DataSource = user;
GridView1.DataBind();
}
我不建议将其用于产品环境,因为它会加载整个表格,但我已将其用于内部应用程序供个人使用。我建议创建一个重载模型。