简体   繁体   English

如何使用实体框架查询外键对象?

[英]How can I query the foreign key objects using Entity Framework?

I am trying to learn about Entity Framework 6, and I am running into an issue, that I have been able to reproduce in a test project:我正在尝试了解 Entity Framework 6,但遇到了一个问题,我已经能够在测试项目中重现该问题:

A Movie has a Name and a Revenue . MovieNameRevenue A Revenue has a GrossIncome : Revenue有总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; }
}

I am trying to use EF6 code-first to persist some data about movies in the database:我正在尝试使用 EF6 代码优先在数据库中保留一些关于电影的数据:

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

I start by inserting a new movie, with its associated revenue in the DB:我首先插入一部新电影,并在数据库中插入其相关收入:

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();
}

I can see in SQL Server that the tables are created, and that a Movies.Revenue_Id column has been created, with a foreign key relationship to Revenue.Id .我可以在SQL Server看到创建表,以及一个Movies.Revenue_Id列已创建,用一个外键关系Revenue.Id

If I try to query it using SQL, it works fine:如果我尝试使用 SQL 查询它,它工作正常:

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

returns返回

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

However, if I try to use Entity Framework to query the data:但是,如果我尝试使用实体框架来查询数据:

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();
}

The console reads:控制台显示:

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.

My question is simple: what am I doing wrong?我的问题很简单:我做错了什么? How are the foreign key values supposed to be read?应该如何读取外键值?

Just include the child entity you want to load:只需包含您要加载的子实体:

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();
}

This will load the movies - and also make sure that all the references to their respective .Revenue references have been loaded, too.这将加载电影 - 并确保所有对各自.Revenue引用的引用也已加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用实体框架保存外键? - How can I save a foreign key using Entity Framework? 如何在Entity Framework的外键字段中添加数据? - How can I add data in foreign key field in Entity Framework? 如何使用实体框架更改外键关联? - How do I change a foreign key association using Entity Framework? 使用实体框架,如何在两个模型上添加外键以相互引用 - Using Entity Framework, how can I add a foreign key on two models to reference each other 如何在Entity Framework 6中使用Fluent API映射没有外键属性的一对多对象列表? - How can I use Fluent API in Entity Framework 6 to Map a List of One To Many objects without a foreign key property? 实体框架使用外键填充子对象 - Entity Framework Populating Child Objects using Foreign Key 如何使用实体框架将外键对象转换为自定义对象? - How to get foreign key objects with entity framework into a custom object? 如何在使用Entity Framework的大型查询中使用外键提高性能? - How to increase performance with a foreign key in a large query with Entity Framework? 我可以使用Entity Framework Code First数据注释创建双向外键关系吗? - Can I create a bidirectional foreign key relationship using Entity Framework Code First data annotations? 使用实体框架时,为什么不能访问外键字段的值? - Why can't I access the value(s) of foreign key field(s) when using Entity Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM