【问题标题】:Retrieving data from related tables with EF 6 and C#使用 EF 6 和 C# 从相关表中检索数据
【发布时间】:2021-06-23 17:43:44
【问题描述】:

我想使用两个表(科学家和国家)从我的数据库中检索数据。 这就是我编写课程的方式

 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!

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

【问题讨论】:

    标签: c# entity-framework-6


    【解决方案1】:

    我相信您正在寻找的概念是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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 2021-05-16
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多