尽管在数据库中正确填充了外键,但外键为空

时间:2013-10-10 23:05:43

标签: entity-framework entity-framework-5

我的上下文中有以下实体:

   public class Asset
    {
        public int AssetId { get; set; }
        public Registration Registration { get; set; }
        [Required]
        [Display(Name = "Asset Type")]
        public AssetType AssetType { get; set; }
        [Required]
        [Range(Constants.SerialNumberStart, Constants.SerialNumberEnd)]
        [DisplayFormat(DataFormatString = "{0:d8}")]
        public int SerialNumber { get; set; }
        [Required]
        [Range(Constants.EquipNumberStart, Constants.EquipNumberEnd)]
        [DisplayFormat(DataFormatString = "{0:d12}")]
        public long EquipNumber { get; set; }
        [Required]
        [Display(Name = "Profile")]
        [Range(Constants.ProfileStart, Constants.ProfileEnd)]
        [DisplayFormat(DataFormatString = "{0:d2}")]
        public int Profile { get; set; }
    }

    public class AssetType
    {
        public int AssetTypeId { get; set; }
        public List<Asset> Asset { get; set; }
        [Required]
        [Display(Name = "Asset Type")]
        [StringLength(40)]
        public string AssetTypeFullName { get; set; }
        [Required]
        [Display(Name = "Asset Alias")]
        [StringLength(8)]
        public string AssetTypeShortName { get; set; }
    }

我已经播种了我的数据库,一切看起来都很好,AssetType外键正确地显示了我的AssetType表数据的索引。

但是当我尝试在下面的代码中为View获取数据时,AssetType键/数据为空。

    public ActionResult Index()
    {
        Logger.Debug("Index");
        RegistrationServerContext dbNotLazy = new RegistrationServerContext();
        return View(dbNotLazy.Assets.ToList());
    }

当我设置断点并检查我的dbNotLazy.Asset数据时,AssetType外键为null。

我认为这可能与Lazy Loading有关,但正如您所看到的,我在View调用之前创建了一个新的上下文。我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

您可能需要使用Include - 更改

return View(dbNotLazy.Assets.ToList()); 

return View(dbNotLazy.Assets.Include("AssetType").ToList());

延迟加载似乎并不总是立即起作用。

相关问题