Linq to Entities中无法构造实体或复杂类型

时间:2021-06-11 06:16:07

EF中在使用linq就行查询select时不能直接使用自动映射生成的类,需要在单独声明一个类或者使用匿名类在查询完成后再转为对应的对象。

   public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (aspnetdbEntities db = new aspnetdbEntities())
{
//MyModel model = new MyModel()
//{
// Name = "andy"
//};
// db.MyModel.Add(model);
// db.SaveChanges();
var result = from a in db.MyModel
select new {id=a.Id, Name=a.Name };
var result2 = from b in db.MyModel
select new MyModel { Id = b.Id, Name = b.Name };
var result3 = from c in db.MyModel
select new TestModel { id = c.Id, Name = c.Name };
var model = result.ToList().Select(a => new MyModel { Id=a.id,Name=a.Name});
var model2 = result2.ToList().FirstOrDefault();
var model3 = result3.ToList().FirstOrDefault();
var model4 = db.MyModel.Select(a=>a).ToList().FirstOrDefault();
} }
}
class TestModel
{
public int id { get; set; }
public string Name { get; set; }
}

Linq to Entities中无法构造实体或复杂类型