我目前正在这样的类中设置属性:
MyClass _Temp = (from x in entities.someTable
select new MyClass {
PropertyONE = x.PropertyONE,
PropertyTWO = x.PropertyTWO
}).FirstOrDefault();
this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;
但是我认为必须有一个更好的方法,比创建另一个类的实例作为占位符只是为了最终填充真实的 - 这样的东西?
this = (from x in entities.someTable
select
PropertyONE = x.PropertyONE,
PropertyTWO = x.PropertyTWO
).FirstOrDefault();
有什么想法吗?
*编辑:更多信息** 我是怎么用的:
在MVC控制器中我有:
public ActionResult Index(Guid id)
{
MyClass model = new MyClass(id);
Return View(model);
}
在“MyClass”的构造函数中,我有上面的代码,我希望它“预加载”类(它的属性),并在视图上显示数据。
希望这能更好地解释它。
答案 0 :(得分:4)
是的,它应该更简单:
var first = entities.someTable.FirstOrDefault();
if(first != null)
{
this.PropertyONE = first.PropertyONE;
this.PropertyTWO = first.PropertyTWO;
}
编辑:将您的代码分层:
数据访问层
public static Entity GetById(int id)
{
using(var entities = new MyEntities())
{
return entities.someTable
.FirstOrDefault(row => row.Id == id);
}
}
控制器层
public ActionResult Index(Guid id)
{
MyClass model;
// call the DAL
var entity = DataAccess.GetById(id);
// call the model
if(entity != null)
{
model = new MyClass(entity);
}
else
{
model = null;
}
Return View(model);
}
模型图层
public class MyClass
{
public MyClass(Entity entity)
{
this.PropertyONE = entity.PropertyONE;
this.PropertyTWO = entity.PropertyTWO;
}
}
答案 1 :(得分:2)
var _Temp = entities.someTable.Select(x=> new{
PropertyONE = x.PropertyONE,
PropertyTWO = x.PropertyTWO
}).FirstOrDefault();
this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;