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 に答える