Search code examples
entity-frameworkef-model-builder

HasMany and WithRequired extension methods not found


I am building my data layer class library with Entity Framework 6.1. I created my context and am trying to do the model builder code (or is it derived when I do Add-Migration?

Anyway, I have seen quite some examples but when I try to use .HasMany or .WithRequired on a modelBuilder.Entity() instance they don't appear in Intellisense. What am I missing?


Solution

  • The Entity<T> method is generic (DbModelBuilder.Entity), so, you need to specify the T type you want to start your configuration, for example:

    public class Foo
    {
      public in Id{get;set;}
    
      public in BooId{get;set;}
    
      public virtual Boo Boo{get;set;}
    }
    
    public class Boo
    {
      public in Id{get;set;}
    
      public virtual ICollection<Foo> Foos{get;set;}
    }
    

    And the configuration on the OnModelCreatingmethod would be:

    modelBuilder.Entity<Foo>().HasRequired(f=>f.Boo).WithMany(b=>b.Foos).HasForeignKey(f=>f.BooId);