1

次のビューモデルを作成しました。

public class PropertyViewModel
{
    public PropertyViewModel(Property property, IList<PropertyImage> images)
    {
        this.property = property;
        this.images = images;
    }

    public Property property { get; private set; }
    public IList<PropertyImage> images { get; private set; }
}

次に、データベース内のすべてのプロパティとそれに関連する画像を取得する関数を作成する必要があります。上記のビューモデルを使用してこれを行うことは可能ですか?私は以下を試しました。

public IList<PropertyViewModel> GetAllPropertyViews()
    {
        IList<PropertyViewModel> properties = null;
        foreach (var property in GetAllProperties().ToList())
        {
            IList<PropertyImage> images = db.PropertyImages.Where(m => m.Property.PropertyID == property.PropertyID).ToList();
            properties.Add(new PropertyViewModel(property, images));
        }
        return properties;
    }

これは機能しません。「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というメッセージが表示されます。でproperties.Add(new PropertyViewModel(property, images));

私が使用しているpaginatationメソッドの場合、IQueryable変数を返す必要があります。任意の提案をいただければ幸いです。

4

1 に答える 1

3

プロパティ変数はですnull。したがって、次のようになります。NullReferenceExceptionを実装する具象クラスのインスタンスで初期化するだけIList<PropertyViewModel>です。

IList<PropertyViewModel> properties = new List<PropertyViewModel>();

より良い解決策はPropertyImages、EFInclude()クエリを使用して1つのクエリですべての関連を取得することです。ただし、リポジトリレイヤー(EFの上にあるように見えます)はこれをサポートする必要があります。現在、データベースでプロパティごとに1つずつ、N個のクエリを実行しています。

編集:

これは、EFInclude()クエリを使用した場合と同等である必要があります。これによりPropertyImages、各プロパティの関連が取得されます。

var properties = db.Properties
                   .Include( x=> x.PropertyImages);
                   .Select( x => new PropertyViewModel(x, x.PropertyImages.ToList())
                   .ToList();
于 2011-09-21T21:52:14.643 に答える