首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.MVCInit模型的国外数据

ASP.MVCInit模型的国外数据
EN

Stack Overflow用户
提问于 2012-11-24 19:39:40
回答 3查看 159关注 0票数 0

下面的模型将" locations“作为表位置中的外键

代码语言:javascript
运行
复制
 public class Restaurant
{
    public int id{ get; set; }
    public string  name{ get; set; }
    public ICollection<Locations> locations { get; set; }
}

为什么当我进入模型餐厅时,位置被设置为null,除非我在调用属性示例之前调用locations上下文:

代码语言:javascript
运行
复制
 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

我怎么能做到当我调用位置时它会自动启动查询..。

EN

回答 3

Stack Overflow用户

发布于 2012-11-24 19:49:27

修改你的访问器。

代码语言:javascript
运行
复制
get
{
  if(!_locations.Any()
  _locations.Add(db.Locations.First();
  return _locations;
}
票数 0
EN

Stack Overflow用户

发布于 2012-11-24 20:19:29

您要求的是延迟加载功能。您使用什么来访问数据(我猜EF)。如果使用EF,则应启用延迟加载。但是要小心,因为懒惰加载可能是邪恶的特性。

到目前为止,如果您希望所有的位置与餐馆对象一起,您可以在restaurant构造函数中自动填充您的位置:

代码语言:javascript
运行
复制
public class Restaurant
{
    public Restaurant() {
       // fill locations
    }

    public int id{ get; set; }
    public string  name{ get; set; }
    public ICollection<Locations> locations { get; set; }
}
票数 0
EN

Stack Overflow用户

发布于 2012-11-24 20:49:19

使用以下代码:

代码语言:javascript
运行
复制
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; }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13544872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档