问题
I am using EntityFramework Core 1.1.0. I can query a table and load entities, but the instructions from Microsoft indicates if I want to load relational data, I should use the .Include()
function:
https://docs.microsoft.com/en-us/ef/core/querying/related-data
You can use the
Include
method to specify related data to be included in query results. In the following example, the blogs that are returned in the results will have theirPosts
property populated with the related posts.using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ToList(); }
I have no .Include()
option.
Any ideas why this is missing or how to load foreign-key relational data?
this.context.Mail
.Include("Files") // This is missing
I have resorted to explicitly loading relational data. This is fine for small result sets, but as my data sets grow, this is going to cause me grief.
var mails = this.context.Mail.ToList();
mails.ForEach(mail =>
{
this.context.Entry(mail)
.Collection(m => m.Files)
.Load();
});
回答1:
Have you included the correct namespaces?
From the repository linked in the documentation:
using Microsoft.EntityFrameworkCore;
using System.Linq;
回答2:
I think your call should be:
this.context.Mail
.Include(m => m.Files).ToList();
For a more detailed answer:
You need to first make sure that your Mail
and File
models are formed correctly so that there is a one-to-many relationship between Mail
and File
:
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; }
}
And then make sure to include Mail
and File
DbSet to your 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)
{
}
}
Then in your controller class or repository class, you can create a method to get Mails with Files like this:
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);
}
回答3:
Add the namespace to get that option.
using Microsoft.EntityFrameworkCore;
and also if you haven't added,
using System.Linq;
If you enable the lazy loading then you don't even need to use include.
来源:https://stackoverflow.com/questions/42098706/entityframework-core-1-1-0-missing-include