Reputation: 8331
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)
{
}
}
Upvotes: 1
Views: 617
Reputation: 125620
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);
Upvotes: 1