EF中在使用linq就行查询select时不能直接使用自动映射生成的类,需要在单独声明一个类或者使用匿名类在查询完成后再转为对应的对象。
1 public partial class WebForm1 : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 using (aspnetdbEntities db = new aspnetdbEntities()) 6 { 7 //MyModel model = new MyModel() 8 //{ 9 // Name = "andy" 10 //}; 11 // db.MyModel.Add(model); 12 // db.SaveChanges(); 13 var result = from a in db.MyModel 14 select new {id=a.Id, Name=a.Name }; 15 var result2 = from b in db.MyModel 16 select new MyModel { Id = b.Id, Name = b.Name }; 17 var result3 = from c in db.MyModel 18 select new TestModel { id = c.Id, Name = c.Name }; 19 var model = result.ToList().Select(a => new MyModel { Id=a.id,Name=a.Name}); 20 var model2 = result2.ToList().FirstOrDefault(); 21 var model3 = result3.ToList().FirstOrDefault(); 22 var model4 = db.MyModel.Select(a=>a).ToList().FirstOrDefault(); 23 } 24 25 } 26 } 27 class TestModel 28 { 29 public int id { get; set; } 30 public string Name { get; set; } 31 }
原文:http://www.cnblogs.com/goodlucklzq/p/4412276.html