使用 EF 6 和 C# 从相关表中检索数据

Retrieving data from related tables with EF 6 and C#

我想用两个 table(科学家和国家)从我的数据库中检索数据。 这就是我编程 class

的方式
 public class Scientist 
    {
        public long ScientistID { set; get; }
        public string Name { set;   get; }
        public string Surname { set; get; }
        public string BornDate { set; get; }
        public string Subject { set; get; }
        public long? CountryID { set; get; }
        
        public virtual Country Country { set; get; }

    }


    public class Country
    {
        public long CountryID { set; get; }

        public string CountryName { set; get; }

        public string Zone { set; get; }

        public virtual List<Scientist> Scientists { set; get; }
    }

    public class PeopleOfScienceContext : DbContext
    {
        public PeopleOfScienceContext() : base("ScientistsConnectionString")
        {
            Database.SetInitializer<PeopleOfScienceContext>(new CreateDatabaseIfNotExists<PeopleOfScienceContext>());
        }

        public DbSet<Scientist> Scientists { get; set; }
        public DbSet<Country> Countries { get; set; }


       
    } 

是否有一种“简单”的方法可以从数据库下载这两个内容,因为它们是相关的? 我的意思是,像这样:

 List<Scientist> scients = ctx.Scientists.ToList(); //ctx was initialized don't worry!

我可以从科学家 table 下载我的所有数据,但我无法下载“CountryName”信息,因为它存储在另一个 table 中并且仍然是空白。 我想避免创建“JOIN”查询;因为我正在学习框架工作,所以我被告知要“编写最低限度”的代码。我的第二个想法是下载两个 tables 并将它们合并到“客户端”,但似乎仍然是任务的无用复杂化(我打赌这种方法不能很好地扩展到大 tables) .我错过了最简单的解决方案还是 EF 6 中没有这样的东西?

我相信您正在寻找的概念是 Eager Loading

尽管您可以在 Linq 查询中明确加入 ScientistCountry 表,因为您已经定义了导航 属性,您应该能够简单地包含导航:

List<Scientist> scientists = ctx.Scientists
   .Include(s => s.Country)
   .ToList()

... 或异步等效项(因为这是 I/O 绑定工作)

var scientists = await ctx.Scientists
   .Include(s => s.Country)
   .ToListAsync();

现在您应该可以像这样取消引用国家/地区了:

scientist.Country.CountryName 

如果关系是可选的(即 CountryId 在数据库中可以为 NULL),那么您可以使用 nullsafe 取消引用运算符:

scientist.Country?.CountryName