繁体   English   中英

实体框架子级为null

[英]Entity framework child is null

我是EntityFramework的新手,所以问题可能有点愚蠢,但我尝试搜索Google却一无所获。

我在db中有一个表:

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    [Required]
    public UserProfile Owner { get; set; }
    [Required]
    public string Mask { get; set; }
    [Required]
    public string Key { get; set; }
    public DateTime Generated { get; set; }
    public DateTime DateTo { get; set; }
    public bool isElite { get; set; }

其中,UserProfile Owner是指向另一个表的链接。 当我这样选择时:

 db.Keys.Where(s=>s.Owner.UserId == WebSecurity.CurrentUserId && s.DateTo > DateTime.UtcNow).ToList()

它运作良好,但是当我尝试通过许可证联系所有者时,它始终为空。 有人可以帮忙如何获得拥有许可的所有者吗? 感谢您的时间!

编辑:我认为我犯了一个错误,并错误地发布了一个问题。 我真正需要的是当我按其ID搜索许可证时,例如: License license = db.Keys.Find(id); 我可以像这样获得所有者: var a = license.Owner; 我以前使用过Active Record,并且“按需”加载了此类数据(仅当我对其进行调用时)。 我可以用EF这样做吗?

使用您拥有的代码,您可以通过在许可证类中将其标记为virtual来延迟加载所有者。

由于您仍处于上下文中(使用db),因此EF会自动调用以充填Owner

有关加载相关实体的好文章, 请查看此内容

编辑(使用linq查询):

这是linq查询的外观示例,但您仍然可能需要懒惰或急于加载所有者。

var query = from k in db.Keys
            where k.Owner.UserId.Equals(WebSecurity.CurrentUserId)
            && k.DateTo > DateTime.UtcNow
            select k;

var list = query.ToList();

利用DbQuery.Include(string path)方法单击此处

至少对我有用。

这是您的代码:

db.Keys.Include(“ Owner”)。其中(s => s.Owner.UserId == WebSecurity.CurrentUserId && s.DateTo> DateTime.UtcNow).ToList()

如果您希望“键”查询返回大量结果,则这可能不是最佳方法。 但是只有有限的结果,它就像一个魅力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM