Sylar
Sylar

Reputation: 41

Creating database through code first EF

I have the following code for my Cliente class

public class Cliente
{
    public Cliente()
    {
    }
    public int id { get; set; }
    public string nome { get; set; }
    public string sobrenome {get;set;}
}

Login class :

public class Login
{
    public Login()
    {
    }
    public int id { get; set; }
    public string login { get; set; }
    public string senha { get; set; }
}

Context class:

public class Context : DbContext
{
    public Context(): base("name=Context")
    {
        Database.Connection.ConnectionString =@"data source=.\SQLEXPRESS;initial catalog=BancoTeste; Integrated Security=SSPI";
    }
    public DbSet<Cliente> Cliente { get; set; }
    public DbSet<Login> Login { get; set; }
}

I'm kinda new to programming, found some examples on the internet and tried to do the same

This code ain't suppose to create a database ?

Upvotes: 1

Views: 95

Answers (4)

Kaf
Kaf

Reputation: 33809

This is another way using Package Manager.

Note: You may need to install Nuget Package Manager using Visual Studio Extension Manager

Locate your Package Manager Console and then run following commands

//(Get the latest version of Entity Framework for you (May not need if you have it))
PM> Install-Package EntityFramework 

// (This will enable database migrations from your model to database)
PM> Enable-Migrations

//(Create a database migration in SolutionExplorer\Migration folder for you)
PM> Add-Migration GiveItAProperName 

//(This will commit those changes to the database or create the database)
PM> Update-Database 

//In the future, if you change your model, do the following to update the database
PM> Add-Migration MyFirstChangesToTheDatabase
PM> Update-Database 

You can add more parameters to above PM commands, please use get-help commandName for more information

Upvotes: 1

Quentin Huet
Quentin Huet

Reputation: 1

Another solution is to use Entity Migration.

You can use commands in package manager console to create new migrations and update your database with your updated model.

Example here

With this solution, you can generate code to upgrade and downgrade your database.

Upvotes: 0

SOfanatic
SOfanatic

Reputation: 5573

Unless you have a Database Initializer set, like @Michael described, then EF will only create your database once you attempt to access it. So for example if you add the following to one of your controllers, EF will create it:

using (var context = new Context())
{
    var allClients = context.Cliente.ToList();
}

Upvotes: 1

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

When you start the application, you need to run this line:

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

Upvotes: 1

Related Questions