Question

For some reason I have started my developing from my database design. Then I used POCO for generating my entitities, entity configurations and the context.

At my next step I would like to make my application create new database if the database specified in connection string of the configuration file does not exist.

The problem I faced at the moment is the following: when I am trying to get FirstOrDefault from a DBSet of my model I am getting the following error message

System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Role'.

I am using the following configuration of my entity

 internal class RoleConfiguration : EntityTypeConfiguration<Role>
    {
        public RoleConfiguration(string schema = "dbo")
        {
            ToTable("Role", schema);
            HasKey(x => x.RoleId);

            Property(x => x.RoleId).HasColumnName("RoleId").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            HasMany(t => t.Roles_RoleId).WithMany(t => t.Roles_ChildRoleId).Map(m =>
            {
                m.ToTable("RoleRoles", schema);
                m.MapLeftKey("ChildRoleId");
                m.MapRightKey("RoleId");
            });
        }
    }
Was it helpful?

Solution

If you want EF to create database for you, you need to set correct initializer in context constructor. For example like this:

public YourContextEntities() : base("name=ConnectionStringName")
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<YourContextEntities>());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top