I have a Entity Framework model set up with text templates to generate the code. However, one of them creates the DBContext containing an OnModelCreating.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
How do expand on this, since a partial class with the same override does not work.
You cannot use OnModelCreating when using model first (EDMX). OnModelCreating is only for scenarios without using EDMX.
Possibly your problem is that the connection string you're using is a standard SQL Server one rather than the Entity Framework one. See this answer.
Related
I've changed from a one-to-many relationship between my two models Workplace and Person. Entity Framework has correctly created the table that connects them and it's named WorkplacePersons and it is also accurately populated. When I try to display a list of people on a workplace I got the exception:
System.Data.SqlClient.SqlException: Invalid object name 'dbo.PersonWorkplaces'
So for some reason it's looking for PersonWorkplaces which doesn't exist, instead of looking for WorkplacePersons
You can define OnModelCreating in your DbContext:
You need to tell Entity Framework which way around you want the mapping, as currently its guessing and getting the tables the wrong way around. in your OnModelCreating add something like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Workplace>()
.HasMany(x => x.Persons)
.WithMany(x => x.Workplaces)
.Map(c =>
{
c.MapLeftKey("WorkplaceId");
c.MapRightKey("PersonId");
c.ToTable("WorkplacePersons");
});
}
In the database I have inherited, the tables are named singularly (i.e. "dbo.Genre"). My mapping code sets the table to be singular as well:
public class GenreMap : EntityTypeConfiguration<Genre>
{
public GenreMap()
{
this.ToTable("Genre");
}
}
However, when I run Add-Migration, the resulting Up() function says...
RenameTable(name: "dbo.Genre", newName: "Genres");
This occurs on all tables, and all of them have the ToTable mapping for singular.
I added the following snippet to the OnModelCreating(DbModelBuilder modelBuilder) function:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
However, it is still not working as expected. Is there anything else that could be causing this to happen?
If you want to remove pluralization of table name it is correct.
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
If you need pluralization of table just comment the above line of code.
I am new to entity framework and mvc, I tried creating a MVC 4 application and do a CRUD operation using entity framework , I created a model "User" and with properties id, firstname , lastname and ran the application , entity framework gave me a table in my database automatically, I wonder how is the background mapping happening here, I see the databaseSetInitializer method is also commented by default. , so how is it creating the database and mapping if I later add or remove records ? On the other end I see in some application they have used mapping by overriding the OnModelCreating event and adding the configuration maps their for each table and the respective columns, so somene please clarify me why is that really used and how did that magically work for me in my trail without these mapping code. ? The code below.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var schemaName = ConfigurationManager.AppSettings["EFSchemaName"];
if (!string.IsNullOrEmpty(schemaName))
{
modelBuilder.Configurations.Add(new UserMap(schemaName));
modelBuilder.Configurations.Add(new BookMap(schemaName));
modelBuilder.Configurations.Add(new CollegeMap(schemaName));
modelBuilder.Configurations.Add(new AreaMap(schemaName));
modelBuilder.Configurations.Add(new StateMap(schemaName));
modelBuilder.Configurations.Add(new LanguageMap(senter code herechemaName));
}
else
{
throw new ConfigurationErrorsException("'EFSchema' setting not found.");
}
}
I'm trying to extend the Asp.NET MVC framework so I can make modules. I want to be able to make separate mini mvc-projects, combine them in the mvc-app and build/install the whole thing. This way I can select the desired modules into one application.
To make the mini MVC projects I want to use this method: http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/
For now I'm trying to make the database build with multiple dbcontexts. I used the IRepository pattern to achieve that. First I made a Entity Framework (4.3) project with this pattern and was able to make a complete database with the OnModelCreating event.
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// /* Use MEF to load all plugins. I'll use the mock interface IPlugin */
List<IContext> Contexts = new List<IContext>();
Contexts.Add(new BikeContext());
Contexts.Add(new CarContext());
Contexts.Equals(new BlogContext());
foreach (IContext context in Contexts)
context.Setup(modelBuilder);
}
}
this is an example function that runs the Setup and is in every subcontext:
public class CarContext : Context, IContext
{
public List<Car> Cars { get; set; }
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>().ToTable("Cars");
modelBuilder.Entity<Car>().HasKey(car => car.Id);
}
}
This repository is from the example given in MEF Plugins and EF CodeFirst - How?
If I use this in a mvc application (which uses the EF on default, right?) the OnModelCreating function does run, so do the setup functions, but it creates neither the database nor the tables. In the end I get an error because the app can't make a connection to the database when it tries to select data. Which is logical because there's no database.
What I basically want is to use the mef-plugins-and-ef-codefirst solution in a MVC app. Am I missing something? Is there another way to create tables manually in your code in MVC/EF?
Well I found the solution myself:
I added this to the index of a controller:
Context context = new Context();
context.Database.CreateIfNotExists();
And changed the public List in the CarContext into public DbSet.
It makes the database with the tables now, and I get the data through CarContext.
I am using NHibernate and ninject in ASP.Net MVC, using this page as a guide. One thing I think is weird is that, in this code (half way down the page)
public class RepositoryModule : NinjectModule
{
public override void Load()
{
const string connectionString = #"Server=localhost; Port=3306; Database=trucktracker; Uid=root; Pwd='your_own_password';";
NHibernateHelper helper = new NHibernateHelper(connectionString);
Bind<ISessionFactory>().ToConstant(helper.SessionFactory).InSingletonScope();
Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
Bind<ISession>().ToProvider(new SessionProvider()).InRequestScope();
Bind<IIntKeyedRepository<Truck>>().To<Repository<Truck>>().InRequestScope();
}
}
I think it's odd that you need to have this line per model:
Bind<IIntKeyedRepository<Truck>>().To<Repository<Truck>>().InRequestScope();
If I have 100 different tables (and thus models) do I really need to add this line in for every class that I have? Is there not a better way where I can just declare this once and use inheritance to pass in the Type in my controller?
Use the Open Generics support:-
Bind(typeof(IIntKeyedRepository<>)).To(typeof(Repository<>)).InRequestScope();