Surprisingly, (and happily) it’s not hard to reference all data inside a class using EF’s codefirst in a 1 to 1 type relationship. Let’s take as an example a very simple relationship where we have a customer who has a detail record. The model definition for this is as follows:
namespace Con1 { public class SiteDB : DbContext { public DbSet<Detail> Details { get; set; } public DbSet<Customer> Customers { get; set; } } public class Customer { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } public string Name { get; set; } } public class Detail { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [ForeignKey("CustomerId")] public Customer Customer { get; set; } public long CustomerId { get; set; } public string DetailDescription { get; set; } } }
The idea is that we want to be able to get to a Customer Name by traversing a Detail record in one step. We need to use the “Include” feature of codefirst to do this. Below is the code that successfully works:
class Program { static void Main(string[] args) { Database.SetInitializer(new SiteDBInitializer()); using (var context = new SiteDB()) { Console.WriteLine(context.Customers.Count()); var details = context.Details.Include(o => o.Customer); foreach (var detail in details) { Console.WriteLine( String.Format( "DetailId: {0} CustomerId: {1} Customer.Name: {2}", detail.Id,detail.CustomerId,detail.Customer.Name)); } } } } internal class SiteDBInitializer : CreateDatabaseIfNotExists<SiteDB> { protected override void Seed(SiteDB context) { context.Details.Add(new Detail { Customer = new Customer {Name = "pkellner"}, DetailDescription = "descr1" }); context.SaveChanges(); } }
When we run this code we get:
Seems simple but it took me a while before I finally decided to make a simple example to prove to myself that this really works.
HTH’s.






[...] my previous post, I showed how to take a simple relationship between Customers and an one Detail per customer build [...]