Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

c# - EF 4.1 OnModelCreating not called

I have a problem with EF 4.1 not calling OnModelCreating so that I can configure tables etc. I have an existing database. Here is my connection string:

<add name="AcmeDBContext"
     connectionString="metadata=res://*/|res://*/|res://*/;
                       provider=System.Data.SqlClient;
                       provider connection string=&quot;
                       data source=[server];
                       initial catalog=Acme;integrated security=True;
                       multipleactiveresultsets=True;App=EntityFramework&quot;"
     providerName="System.Data.EntityClient" />

Here is my class inherited from DbContext:

public class AcmeDBContext : DbContext
{
  public AcmeDBContext()
    : base()
  {
    Database.SetInitializer<AcmeDBContext>(null);        
  }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();       
    modelBuilder.Entity<Vehicle>().ToTable("tblVehicle");
    modelBuilder.Entity<VehicleMake>().ToTable("tblVehicleMake");
    modelBuilder.Entity<VehicleModel>().ToTable("tblVehicleModel");
    base.OnModelCreating(modelBuilder);
  }

 }

I have read and read online, but I cannot point out what the problem is. The OnModelCreating is never called and hence the exceptions saying that the entity/classes (Vehicle, VehicleMake, VehicleModel) do not exist in the current context when I try to query anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using two approaches together - your connection string says that you want to use model first or database first with EDMX but you are writing context to use code first / fluent api to map database. Once you use EDMX OnModelCreating is never called. Use common SQL connection string without metadata resources if you want to use OnModelCreating.

<add name="AcmeDBContext"
     connectionString="data source=[server];
                       initial catalog=Acme;integrated security=True;
                       multipleactiveresultsets=True;App=EntityFramework"
     providerName="System.Data.SqlClient" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...