0

我目前正在这样的类中设置属性:

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”的构造函数中,我有上面的代码,我希望它“预加载”类(它的属性),并在视图上显示数据。

希望这能更好地解释它。

4

2 回答 2

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;
    }
}
于 2013-04-30T14:26:00.900 回答
2
var _Temp = entities.someTable.Select(x=> new{
                                               PropertyONE = x.PropertyONE,
                                               PropertyTWO = x.PropertyTWO 
                                             }).FirstOrDefault();
this.PropertyONE = _Temp.PropertyONE;
this.PropertyTWO = _Temp.PropertyTWO;
于 2013-04-30T14:25:09.197 回答