none
EF Code first relation without key in both table (how to?) RRS feed

  • Question

  • public class Foo {
      public int Id {get;set;}
      public virtual Bar Bar {get;set;}
    }
    
    public class Bar {
      public int Id {get;set;}
    
      public int FooId {get;set;}
      public virtual Foo Foo {get;set;}
    }

    I want to setup the relation as above, but without store the BarId in Foo table
    Foo have optional Bar, Bar have required Foo

    i expect Foo table have column (Id)
    and Bar table have column(Id, FooId)

    but Foo still have reference(lazy load) to Bar

    thank you very much.

    Wednesday, October 9, 2013 4:17 PM

Answers

  • Hello,

    From your description, if I understand correctly, you want to build a one-to-one relationship.

    With your code, I made a sample and please see it below:

    public class FooDbContext : DbContext
    
        {
    
    
            public DbSet<Bar> Bars { get; set; }
    
            public DbSet<Foo> Foos { get; set; }
    
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
    
            {
    
                modelBuilder.Entity<Bar>().Property(bar => bar.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
    
                modelBuilder.Entity<Foo>().Property(foo => foo.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
    
                modelBuilder.Entity<Bar>().HasRequired(bar => bar.Foo).WithOptional(foo => foo.Bar);
    
            }
    
    }
    

    For achieving what you want, we need to override the OnModelCreating() method and use the Fluent API to specify the one-to-one relationship.

    And for the lazy load, actually when we use virtual, we already use it.

    For more information about lazy load:

    http://msdn.microsoft.com/en-us/data/jj574232.aspx

    If I have misunderstood, please let me know.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 10, 2013 5:57 AM
    Moderator