下面的模型将" locations“作为表位置中的外键
public class Restaurant
{
public int id{ get; set; }
public string name{ get; set; }
public ICollection<Locations> locations { get; set; }
}
为什么当我进入模型餐厅时,位置被设置为null
,除非我在调用属性示例之前调用locations上下文:
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
我怎么能做到当我调用位置时它会自动启动查询..。
发布于 2012-11-24 19:49:27
修改你的访问器。
get
{
if(!_locations.Any()
_locations.Add(db.Locations.First();
return _locations;
}
发布于 2012-11-24 20:19:29
您要求的是延迟加载功能。您使用什么来访问数据(我猜EF)。如果使用EF,则应启用延迟加载。但是要小心,因为懒惰加载可能是邪恶的特性。
到目前为止,如果您希望所有的位置与餐馆对象一起,您可以在restaurant构造函数中自动填充您的位置:
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-24 20:49:19
使用以下代码:
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; }
}
https://stackoverflow.com/questions/13544872
复制相似问题