Entity Framework Connection String

2

I'm creating a project using Entity Framework.

My question, would be, how can I create a connectionString (for SQL Server for example) and set in my DBContext where it will get from the Web.config file?

DBContext

namespace Data
{
    public class DBContext : DbContext
    {
        public DBContext() : base("dbName")
        {

        }

        public DbSet<Usuarios> Clientes { get; set; }
        public DbSet<Vendedores> Produtos { get; set; }

    }
}
    
asked by anonymous 29.04.2017 / 16:25

1 answer

2

Your connectionStrings should look like this in web.config:

To create in LocalDB:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Nome_Arquivo.mdf;Initial Catalog=Nome_Arquivo;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

To create in SQL Server (if you have it installed):

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Nome_BD;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

The first connectionStrings string is automatically created in your web.config when you start an MVC project with EF. Make sure it does not already exist before you create it, and if you want, change to the second example.

You do not need to point to your DBContext. If you want the database already created (CodeFirst), enable Migrations in Package Manager Console by typing:

  

Enable-Migrations

After this the Migrations directory will appear in your project. Open the file Configuration.cs in this directory and enable the options below:

public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

With these settings you can now use the command below in Package Manager Console :

  

Update-Database

This command will create your Database. The MDF file will appear in the App-Data folder (if you created a LocalDB) and if you click Show all files you can open it to see your database in Server-Explore .

If you created it in SQL Server, just open Management Studio to see the database.

Your DbContext should look like this (already with the 2 DbSet of your question):

public class DBContext : DbContext
    {
        public DBContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static DBContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet<Usuarios> Clientes { get; set; }
        public DbSet<Vendedores> Produtos { get; set; }
    }
    
29.04.2017 / 17:12