Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc entity framework code first create database if not exist

I have an issue with entity framework . I am using code first approaching but it is not create the database. It is throw an error with following codes in global.asax:

using (resimupDeneme.Data.DataContext db = new DataContext())
        {
            db.Database.CreateIfNotExists();
        }

Here is my picture class :

public class foto
{
    public int fotoId { get; set; }

    [Required(ErrorMessage="fotoğraf yolu zorunludur")]
    [DataType(DataType.ImageUrl)]
    public string uzanti{ get; set; }

}

And my context class :

public class DataContext : DbContext
{


    public DataContext() //i find this codes from internet for a solution for my problem but it is not worked 
        : base("DataContext")
    {
        Database.SetInitializer<DataContext>(new CreateDatabaseIfNotExists<DataContext>());
    }

    public DbSet<foto> fotos { get; set; }

}
like image 545
Emre Savcı Avatar asked Feb 13 '26 02:02

Emre Savcı


1 Answers

You said in comments:

it is not throw ride now (interesting) but when i try to see database on sql server object explorer it is not there

Have you actually targeted Sql Server for use with your project?

 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">

By default it targets localdb

<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework">

Do you have a connection string in your web.config called "DataContext" and if so is it pointing at your SqlServer instance?

..

Beyond that you're doing the same thing multiple times. Remove this from your using.

db.Database.CreateIfNotExists();

And lift this from DataContext:

 Database.SetInitializer<DataContext>(new CreateDatabaseIfNotExists<DataContext>());

and put it either directly into Application_Start() or create a EfDatabaseConfig class with a static Config method and call it from Application_Start().

EfDatabaseConfig.Configure();

Or just use the web.config:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v12.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
      <context type=" Blogging.BlogContext, MyAssembly">
        <databaseInitializer type="System.Data.Entity.CreateDatabaseIfNotExists`1[[Blogging.BlogContext, MyAssembly]], EntityFramework" />
      </context>
    </contexts>
  </entityFramework>
like image 176
rism Avatar answered Feb 15 '26 06:02

rism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!