0

テーブルの場所からの外部キーとして「場所」を持つ次のモデルがあります

 public class Restaurant
{
    public int id{ get; set; }
    public string  name{ get; set; }
    public ICollection<Locations> locations { get; set; }
}

nullモデルレストランを初期化するたびに、属性の例を呼び出す前にロケーションDBコンテキストを呼び出した場合を除いて、ロケーションが設定されるのはなぜですか。

 var t = db.Restaurant.First(); // the locations attribute is null
 db.Locations.First(); // calling the locations db context
 t; // now t.locations has one record without adding anything just loading the DB

場所を呼び出すたびにクエリを自動的に開始するにはどうすればよいですか...

4

3 に答える 3

0

以下のコードを使用してください。

public class Restaurant
{
    public Restaurant()
    {
        locations = new List<Locations>();
    }

    public int id{ get; set; }
    public string  name{ get; set; }
    public ICollection<Locations> locations { get; set; }
}
于 2012-11-24T20:49:19.593 に答える
0

あなたが求めているのは遅延読み込み機能です。データ アクセスには何を使用しますか (EF だと思います)。EF を使用する場合は、遅延読み込みを有効にする必要があります。ただし、遅延読み込みが悪い機能になる可能性があるため、注意してください。

これまでのところ、すべての場所をレストラン オブジェクトと一緒に使用したい場合は、レストラン コンストラクターで場所を自動的に埋めることができます。

public class Restaurant
{
    public Restaurant() {
       // fill locations
    }

    public int id{ get; set; }
    public string  name{ get; set; }
    public ICollection<Locations> locations { get; set; }
}
于 2012-11-24T20:19:29.920 に答える
0

get アクセサーを変更します。

get
{
  if(!_locations.Any()
  _locations.Add(db.Locations.First();
  return _locations;
}
于 2012-11-24T19:49:27.693 に答える