Unable to add DbModelBuilder and .HasRequired() to modelBuilder

5.1k views Asked by At

I am trying to create a ModelBuilder within my API and can't seem to add .HasRequired() to my code. I am assuming this is due to the fact that it lives within DBModelBuilder, however, I cannot add that also.

It will only allow me to use ModelBuilder. Otherwise it throws an error: OnModelCreating(DbModelBuilder): no suitable method found to override

Am I missing something here?

My DbContext looks like so:

public class TicketContext : DbContext
    {
        public DbSet<Tickets> Tickets { get; set; }
        public DbSet<Users> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) // <-- Not allowing me to add DbModelBuilder here
        {
            modelBuilder.Entity<Tickets>().HasRequired(t => t.Users);

        }
    }

Update

I have (as a test) started a new project from scratch. I created a new ASP.NET 5.0 project using a Web API template. Straight away my project doesn't recognize DbModelBuilder. I added reference to EntityFramework.dll and still no good. I then added using System.Data.Entity; and it then accepted DbModelBuilder but still complains that the namespace 'DbModelBuilder' could not be found.

I can't understand how I can have this error upfront on a brand new project?

As soon as I try and add the package Entity Framework from NuGet, I get more errors that version 6.1.3 is not compatible with DNX Core 5.0

I can't seem to find any examples/solutions to any of these errors.

Update 2

I have managed to get DbModelBuilder recognized now by adding the EntityFramework.dll reference to the DNX Core 5.0 Assembly as well as the DNX 4.5.1 assembly, however, now it has thrown even more errors wanting System.Core added and mscorlib. I really can't believe how much trouble it is to create a (what I thought would be simple) Web API project.

1

There are 1 answers

9
Steve Greene On

You can't just call HasRequired off the model builder - you need to indicate the entity you want to change:

public class MyContext: DbContext 
{ 
    public DbSet<Foo> Foos { get; set; } 
    public DbSet<Bar> Bars { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        modelBuilder.Entity<Foo>().HasRequired(f => f.Bar);   // assumes Bar navigation added to Foo
    } 
} 

https://msdn.microsoft.com/en-us/data/jj591617.aspx?f=255&MSPPError=-2147217396

What I like to do is separate out my fluent code like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
       modelBuilder.Configurations.Add(new FooConfig());
    } 

Now I can create a class with all my mapping for that entity:

public class FooConfig : EntityTypeConfiguration<Foo>
{
    public FooConfig()
    {
        // Primary Key
        this.HasKey(t => t.FooId);

        // Relationships
        this.HasRequired(f => f.Bar).WithMany(b => b.Foos);

    }
}