简体   繁体   中英

Retrieving data from related tables via EF6 and Linq

I've used the Code First process to create several SQL tables.

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= 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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