简体   繁体   English

通过EF6和Linq从相关表中检索数据

[英]Retrieving data from related tables via EF6 and Linq

I've used the Code First process to create several SQL tables. 我已经使用“代码优先”过程创建了多个SQL表。

public class Person
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public TitleType Title { get; set; }
}
public class TitleType
{
public int Id { get; set; }
public string Name { get; set; }
}

In my code I am using the following syntax to retrieve a Person. 在我的代码中,我使用以下语法检索Person。

Person person= db.Persons.Find(id);

I an access the attributes of the person properly but shouldn't I be able to access the TitleType Name property with 我可以正确访问人员的属性,但是我不能通过以下方式访问TitleType名称属性

var MyTitle = person.Title.Name;

Is my code first code structured correctly or do I need to change some relationship? 我的代码优先代码结构正确还是需要更改某些关系? Currently it just returns a null. 当前它只返回一个空值。


Here is my Context class 这是我的上下文课

 public partial class MyContext : DbContext
{
    static MyContext()
    {
        Database.SetInitializer<MyContext>(null);
    }
    public MyContext()
        : base("Name=MyContext")
    {
    }
   public DbSet<Person> Persons{ get; set; }
   public DbSet<TitleType> TitleTypes { get; set; }

           protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }               
}

Looks like you have lazy loading disabled. 看起来您已禁用延迟加载。 Try following to load Title property content eagerly: 尝试执行以下操作以急切地加载Title属性内容:

Person person= db.Persons.Include("Title").FirstOrDefault(x => x.Id == id);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM