Search code examples
entity-frameworkef-code-firstlazy-loadingentity-framework-ctp5

How can I have a Foo with exactly one Bar in EF 5 Code First


I'm a gibbering wreck trying to get EF code first to let me do something that I could do in 2 minutes in SQL. Had I not already spent 5 days trying to get it to work, I'd just code up my database in DDL and use ADO.NET. But I digress...

I want to have 2 tables, where each record in A has a corresponding record in B. They're both part of the same object; they need to be in separate tables for reasons I won't go into (but they really do, so don't go there). If I were designing it from the database end, I'd simply have an FK relationship from B to A. Job done.

In EF Code First, I've tried using both the shared primary key method and the one-to-one foreign key association method, and neither work for me. I've also tried 100 or so combinations of all the variants I can think of, and I'm no further forward.

As I said, all I want is there to be a navigable relationship from A to B (and back would be nice, but I've read that's not possible), and for that relationship to be lazy-loaded, so that I can say a.b and have access to the fields of b.

I can't possibly enumerate all the things I've tried, so let me just give an example of what nearly works:

class Foo
{
    public int Id { get; set; }
    public string FooProperty { get; set; }

    public virtual Bar Bar { get; set; }
}

class Bar
{
    public int Id { get; set; }
    public string BarProperty { get; set; }
}

Note that there's no back-reference from Bar to Foo, since (a) SQL Server would complain about multiple cascade delete paths, and (b) EF would complain about not knowing which side is the principal end of the association. So... fine - I can live without it.

What this gets me in the database is a Foos table with Id, FooProperty and Bar_Id fields, and a Bars table with Id and BarProperty fields. That's pretty close to they way I'd model it in SQL, although I'd probably put the FK field in Bar rather than Foo. But since it's 1:1 it doesn't really matter, I guess.

The reason I say that this nearly works is that if I add a Bar and associated Foo and then load them back in, the Bar property of the Foo object is null.

using (var dbContext = new MyDbContext())
{
    var foo = dbContext.Foos.Create();
    foo.FooProperty = "Hello";
    dbContext.Foos.Add(foo);

    var bar = dbContext.Bars.Create();
    bar.BarProperty = "world";

    foo.Bar = bar;

    dbContext.SaveChanges();
}

using (var dbContext = new MyDbContext())
{
    foreach (var foo in dbContext.Foos)
        Console.WriteLine(foo.Bar.Id); // BOOM! foo.Bar is null
}

I would normally expect the evaluation of foo.Bar to trigger lazy-loading of the Bar object, but it doesn't - that property remains null.

How can I fix it?


Solution

  • Thsi should work:

    Context

    public class FoobarCtx : DbContext
    {
        public DbSet<Bar> Bars { get; set; }
        public DbSet<Foo> Foos { get; set; }
    
        public FoobarCtx()
        {
    
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Bar>()
                .HasRequired(f => f.Foo)
                .WithRequiredDependent(b => b.Bar)
                .Map(x => x.MapKey("FooId"))
                .WillCascadeOnDelete(true);
        }
    }
    

    Entities

    public class Foo
    {
        public int Id { get; set; }
    
        public string Foo1 { get; set; }
        public string Foo2 { get; set; }
    
        public virtual Bar Bar { get; set; }
    }
    
    public class Bar
    {
        public int Id { get; set; }
        public string Bar1 { get; set; }
        public string Bar2 { get; set; }
    
        public virtual Foo Foo { get; set; }
    }
    

    I tested it in EF 4.3, but I think it should work also in EF5. The Key is the OnModelCreating method. There you can define either one or the other as the principal/descendant and get rid of the Microsoft SQL restriction.

    For more information see this blog-post. For more information about the model builder (fluent API), go here.

    To enable lazy loading, use the DbContext.FooSet.Create() method. Example here.