如何使用Entity Framework查询外键对象?

时间:2019-02-07 16:49:59

标签: c# sql-server entity-framework entity-framework-6

我试图了解Entity Framework 6,但遇到一个问题,我已经能够在测试项目中重现该问题:

Movie有一个Name和一个RevenueRevenue具有GrossIncome

public class Movie
{
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public Revenue Revenue { get; set; }
}

public class Revenue
{
        [Key]
        public int Id { get; set; }
        public double GrossIncome { get; set; }
}

我正在尝试先使用EF6代码将一些有关电影的数据保存在数据库中:

public class MovieContext: DbContext
{
    public MovieContext(): base("name=testDB") { }
    public DbSet<Movie> Movies { get; set; }
    public DbSet<Revenue> Revenues { get; set; }
}

我首先插入一部新电影,并将其相关收入收入数据库:

using (var context = new MovieContext())
{
    Revenue revenue = new Revenue()
                {
                    GrossIncome = 10
                };
    Movie movie = new Movie()
                {
                    Name = "foo",
                    Revenue = revenue
                };

    context.Movies.Add(movie);
    context.SaveChanges();
}

我可以在SQL Server中看到已经创建了表,并且已经创建了Movies.Revenue_Id列,并具有与Revenue.Id的外键关系。

如果我尝试使用SQL查询它,则效果很好:

SELECT Movies.Name, Revenues.GrossIncome
FROM Movies
LEFT JOIN Revenues ON Movies.Revenue_Id = Revenues.Id

返回

Name    GrossIncome
----------------------
foo         10

但是,如果我尝试使用Entity Framework查询数据:

using (var context = new MovieContext())
{
    List<Movie> movieList = context.Movies.ToList();
    Console.WriteLine("Movie Name: " + movieList[0].Name);

    if (movieList[0].Revenue == null)
    {
        Console.WriteLine("Revenue is null!");
    }
    else
    {
        Console.WriteLine(movieList[0].Revenue.GrossIncome);
    }

    Console.ReadLine();
}

控制台显示:

Movie Name: foo     <- It shows that the query works, and that the data in the main table is fetched.
Revenue is null!    <- Even though the data in the DB is correct, EF does not read the data from the foreign key.

我的问题很简单:我做错了什么?应该如何读取外键值?

1 个答案:

答案 0 :(得分:2)

只需包括您要加载的子实体:

S = c + d

这将加载电影-并且还确保已加载对它们各自的using (var context = new MovieContext()) { List<Movie> movieList = context.Movies .Include(m => m.Revenue) // ADD THIS INCLUDE .ToList(); Console.WriteLine("Movie Name: " + movieList[0].Name); if (movieList[0].Revenue == null) { Console.WriteLine("Revenue is null!"); } else { Console.WriteLine(movieList[0].Revenue.GrossIncome); } Console.ReadLine(); } 引用的所有引用。