K
K
Kcid132014-07-13 10:18:10
Database
Kcid13, 2014-07-13 10:18:10

How to properly connect a DB in ASP.NET MVC 4?

I am developing an ASP.NET MVC 4 application using the Entity Framework with a Code First approach.
Course of action: I create a Sql Server DB, and a connection to it appears in Server Explorer, I describe business logic models, I create a context for the database based on DbContext, I create a connection string in Web.config, I use the string from the connection properties as a string created by me at the beginning.
When the application is launched, tables for the Simple MembershipProvider appear in the database I created, the rest of the models are not displayed in any way, model changes also do not affect the database in any way. I looked at what connections there are to the LocalDb server - it turned out that a local database is being created, in which there are tables for all the models I described, which is actually used in the application.
I follow the conventions for naming models and context, the connection string, since it is offered by Visual Studio, must be a priori correct.
Actually the question is: how do you still need to connect to the created database so that it is used, and not a new one is created?
PS After changing the model and running the application, I once again discovered that the database I created had suddenly changed, and instead of the local database, another newly created one was used. After that, when repeating similar actions, this behavior is no longer observed. Now I'm completely confused.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2014-07-13
@Kcid13

You need to not just run the application (how the application knows that you need to create tables based on models), but refer to the data
context context for the database, for example:

public class DbEntity : DbContext
    {
        public DbSet<Player> Players { get; set; }
        public DbSet<Team> Teams { get; set; }
    }

If you create a database in the App_Data folder, then the connection string should look like this:
<connectionStrings>
    <add name="DbEntity" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\YourBase.mdf';Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

A
Alexey Gagarin, 2014-08-14
@Alexey_Gagarin

Here, read about initializers www.codeguru.com/csharp/article.php/c19999/Underst...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question