【问题标题】:EntityFramework Core 1.1.0 missing Include()? [duplicate]EntityFramework Core 1.1.0 缺少 Include()? [复制]
【发布时间】:2023-03-03 03:14:01
【问题描述】:

我正在使用 EntityFramework Core 1.1.0。我可以查询表并加载实体,但微软的说明表明如果我想加载关系数据,我应该使用.Include() 函数:

https://docs.microsoft.com/en-us/ef/core/querying/related-data

您可以使用Include 方法指定要包含在查询结果中的相关数据。在以下示例中,结果中返回的博客的Posts 属性将填充相关帖子。

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ToList();
}

我没有.Include() 选项。

任何想法为什么会丢失或如何加载外键关系数据?

this.context.Mail
    .Include("Files") // This is missing

我已经诉诸于显式加载关系数据。这对于小型结果集来说很好,但随着我的数据集增长,这会让我很伤心。

var mails = this.context.Mail.ToList();
mails.ForEach(mail =>
{
    this.context.Entry(mail)              
    .Collection(m => m.Files)
    .Load();
});

【问题讨论】:

  • 你能告诉我们你是如何在邮件类中为关系表建模的吗?
  • Dai.. 您的编辑适用于 EF6 及更低版本。我正在使用 EF-Core... 该版本中的 DbSet 似乎没有“Include()”选项。
  • Dai...我可能缺少一个 nuget 包,但据我所知,Entity Framework Core 中没有 Include()。我知道你分享的文档说它们是针对 Core 的,我今天已经阅读了好几次......这些文档是我问这个问题的原因......它说使用 Include(),但我没有那个选项。
  • 要通知某人,你需要这个语法:@Dai。我现在已经为你做到了。此外,他只是改进了你的问题,因为你错过了提供你的研究来源。 (微软表示如果我想加载关系数据,我应该使用 .Include() 函数
  • @ChristianGollhardt - 感谢您的提示!我对在这里提问很陌生。我看到他没有尝试回答。

标签: c# entity-framework entity-framework-core


【解决方案1】:

您是否包含了正确的命名空间?

From the repository linked in the documentation:

using Microsoft.EntityFrameworkCore;
using System.Linq;

【讨论】:

【解决方案2】:

添加命名空间以获得该选项。

using Microsoft.EntityFrameworkCore;

如果你还没有添加,

using System.Linq;

如果你启用延迟加载,那么你甚至不需要使用包含。

【讨论】:

    【解决方案3】:

    我认为你的电话应该是:

    this.context.Mail
        .Include(m => m.Files).ToList();
    

    如需更详细的答案: 您需要首先确保您的MailFile 模型正确形成,以便MailFile 之间存在一对多的关系:

    public class Mail
    {
        public int MailId { get; set; }
    
        public virtual ICollection<File> Files { get; set; }
    }
    
    public class File
    {
        public int FileId { get; set; }
    
        public int MailId { get; set; }
        public virtual Mail Mail { get; set; }
    }
    

    然后确保将 MailFile DbSet 包含到您的 DbContext 中:

    public class MailingContext : DbContext
    {
        public MailingContext(DbContextOptions options) : base(options)
        {
        }
    
        public DbSet<Mail> Mails { get; set; }
        public DbSet<File> Files { get; set; }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
        }
    }
    

    然后在您的控制器类或存储库类中,您可以创建一个方法来获取带有文件的邮件,如下所示:

    public IList<Mail> GetMails()
    {
        return _context.Mails.Include(m => m.Files).ToList();
    }
    
    public Mail GetMailById(int id)
    {
        return _context.Mails.Include(m => m.Files).SingleOrDefault(m => m.MailId == id);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 2015-03-01
      • 2017-05-26
      • 2012-09-19
      • 1970-01-01
      • 2013-09-01
      相关资源
      最近更新 更多