Where is my MVC 5 code-first database created? (not using AttachDbFilename) - asp.net-mvc

I have the following connection string in my MVC 5 weApp:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;User Instance=True;Initial Catalog=MatWebDB;Integrated Security=True" providerName="System.Data.SqlClient" />
I'm using Entity Framework code-first and Identity 2 for forms authentication.
Evreything seems to work fine: i register a new user and it logs in properly.
The problem is that i cannot find the database that was created; in my SQL Server Management Studio there is no "MatWebDB" database created.
What i want to do is to use the same database generated automatically by the Identity 2 authentication, for my own POCO entity objects. And know where is it created.
Thanks!

The easiest way to combine them is to have your application context inherit from the identity context and set the connection string there:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// Use an initializer that will create the database, or create it in SSMS first
Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDbContext>());
}
// Your identity and application tables will be created in the database this connect string points to
public ApplicationDbContext()
: base("DefaultConnection", false)
{ }
// define your POCOs here
public virtual DbSet<Foo1> Foo1s { get; set; }
public virtual DbSet<Foo2> Foo2s { get; set; }
.. etc
}

Very simply. In your Web.config
<configuration>
<connectionStrings>
Using code first and Sqlserver:
If you have a local database you use a connection string like so:
<add name="DefaultConnection1" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
AttachDbFilename=|DataDirectory|\aspnet-WebApplicationMVC-xxxx.mdf;
Initial Catalog=aspnet-WebApplicationMVC-xxxxx;Integrated Security=True"
providerName="System.Data.SqlClient" />
To see the database in visual studio:
If you have a database hosted on an online server:
<add name="DefaultConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=SQLxxxxx;integrated security=false;
Initial Catalog=DB_9D914B_kermit;User Id=DBxxxxx;Password=xxxx;
Trusted_Connection=false;TrustServerCertificate=false;Encrypt=False;
MultipleActiveResultSets=True" />
To see the database in SQL server management studio:
The security attributes of the connection strings can be varied to suit your needs.

Step 1:
In Solution Explorer, there is a default folder named "App_Data" firstly, just click to select this folder.
Step 2:
Now click the above menu bar icon i.e "show all" as shown in the below image.
You will find your db there, just double click on db file,for editing or add new tables.

Related

Unable to use two connection string in web.config file. One is EntityConnection string Database first and other one is normal DBConnection

I am facing problem when I am using two connection string in my web.config file.
One connection string is simple DefaultDBConnection which is used for account controller.
Another connection is EntitiesConnection string Database first approach. This connection string is used to process SELECT operation using my stored procedure and this connection string is completely used in separate controller.
When i use both the connection string. Only EntitiesConnection string works and the operations on account controller does not work.
Can any one help me to fix this. I have been searching from past two days but unfortunately i did not find any solution.
Below is my two connection string in web.config.
<add name="DefaultDBConnection" connectionString="Data Source=xyz;Initial Catalog=My_DB;User ID=abc;pwd=abc123" providerName="System.Data.SqlClient" />
<add name="EntitiesConnection" connectionString="metadata=res://*/EntityModel.Model1.csdl|res://*/EntityModel.Model1.ssdl|res://*/EntityModel.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=xyz;initial catalog=My_DB;user id=abc;password=abc123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
swap the names in the config make DefaultDBConnection ==EntitiesConnection and EntitiesConnection ==DefaultDBConnection
Check identityModel.cs file in the models folder, whether base name is same as the connection string name,
public ApplicationDbContext()
: base("DefaultDBConnection", throwIfV1Schema: false)
{
}
In the web config;
<add name="DefaultDBConnection" connectionString="Data Source=xyz;Initial
Catalog=My_DB;User ID=abc;pwd=abc123" providerName="System.Data.SqlClient" />

Connection string EF Code First

I started an application using Entity Framework Code First.
In my Web.config I added the connection string:
<add name="MyContext" connectionString="Data Source=server\mssqlserver2008;Initial Catalog=dbname;persist security info=True; Integrated Security=SSPI" providerName="System.Data.SqlClient" />
And I received a error when I tried to access my Controller: CREATE DATABASE permission denied in database 'master'
So, I debugged the code and I found that the attribute "ConnectionString" inside my Context it's different from my Web.config:
Data Source=.\\SQLEXPRESS;Initial Catalog=MyProject.Models.MyContext;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFrameworkMUE
Why the ConnectionString is wrong??
In your EF initialization code, make sure you specify the connection string name like this
public class MyDbContext : DbContext
{
public MyDbContext() : base("MyContext") {}
}

I cannot locate where mvc4 store its database

I am very new to MVC4 and try to learn everything by doing a simple project. I created a model and a control succesfully. But I couldnt understand where it stores its database.
I can do insert,delete,update records on webpage created by ASP.NET, but I cannot locate where that database is. I checked the web.config but there is no connection string. how can I find out where the system stores its data?
I have sql-server installed on my computer but I checked it and it is not stored there
MVC4 stores the database in an mdf file located in your App_Data folder. The connection string is available in the top-level web.config.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication6-20130610160316;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication6-20130610160316.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(#"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}

Splitting an Solution into multiple projects

I created a Black Solution (Arhi) with a ASP.NET MVC 4 Internet project (Arhi.Core) and Class library project for data (Arhi.Data) where I'm storing my EDMX Model.
I added a reference for Arhi.Data into Arhi.Core and I tried to add a Controller with a Model class from Arhi.Data (People entity) and I got this error.
'Unable to retrive metadata for 'Arhi.Core.People'. The specified
named connection is either not found in the configuration, not
inteneded to be used with the EntityClient provider, or not valid.'
Q : Why did I get this error ? Is my approach wrong / any recommendations?
Q2 : If I want to add RDLC reports to my solution, should I also use a Class Library project ?
Connection string from Arhi.Core
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-SalvamontMVC-20121108140556;Integrated Security=SSPI" />
and Arhi.Data
<add name="SalvamontEntities" connectionString="metadata=res://*/ModelSalva.csdl|res://*/ModelSalva.ssdl|res://*/ModelSalva.msl;provider=System.Data.SqlClient;provider connection string="data source=www.arhimedes.ro,1433;initial catalog=Salvamont;persist security info=True;user id=sa;password=********;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
in your first connection string not have user name and password if two database deference then give user name and password in first connection string

How to set manually an Oracle Connection String in a DbContext

I have the following connection string:
<add name="DataContext" connectionString="DATA SOURCE=Server;
PASSWORD=123;USER ID=SYSTEM" providerName="Oracle.DataAccess.Client"/>
My business logic determine I need to read manually the connection string of the database:
class MyDbContext: DbContext
{
public MyDbContext() :
base(ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString){}
...
}
It works properly with Sql Server but when I change to a Oracle Connection string don't works. It happens because the DbContext tries to use the Oracle ConnectionString to connect on a Sql Server Database because it dinn't receive the providerName.
Anyone knows how to solve this problem?
To create a DbContext using Oracle without use WebConfig, your inheritance of DbContext must inject an Oracle Connection to base constructor:
class MyDbContext: DbContext
{
public MyDbContext() : base(new OracleConnection("DATA SOURCE=Server; PASSWORD=123;USER ID=SYSTEM"){}
...
}
Just found the solution after struggling with this all afternoon. Seems that the constructor or DbContext will use either the connection string or connection string name, which is not the same, if you pass a connection string it will default to SqlClient which is the only thing bundled by default in .NET
Now, if you, instead of using the whole connection string, pass just the connection string name then it will internally parse also the "providerName" parameter which has the assembly name for the DB provider Oracle.DataAccess.Client for instance.
So instead of passing the connection string to the DbContext constructor just pass the connection string name, like this:
.config file:
<connectionStrings>
<add name="SQLServer" connectionString="Server=localhost; Database=MyDb; User ID=MyUser;Password=MyPwd;Pooling=false" providerName="System.Data.SqlClient" />
<add name="Oracle" connectionString="Data Source=localhost:1521/XE;Persist Security Info=True;User ID=MyUser;Password=MyPwd;" providerName="Oracle.ManagedDataAccess.Client"/>
</connectionStrings>
<appSettings>
<add key="DefaultConnection" value="Oracle" />
</appSettings>
And in your DbContext:
public MyDbContext()
: base("DefaultConnection")
{
}
That way you just set up a config key with the name of the connection string you want to hook the context to and use it in the constructor. If you do it this way EF will automatically parse the whole connection string tag and not only the connectionString attribute value, hence, load the right provider.
Do note that I'm using Oracle.ManagedDataAccess.Client which is newer and only included in ODAC / ODP.NET v12 and above. If you use ODAC 11 you should use Oracle.DataAccess.Client in providerName instead.
Got it working by specifying "Default Connection Factory" in web/app .config
<configuration>
...
<entityFramework>
<defaultConnectionFactory type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework" />
<providers>
...
https://docs.oracle.com/cd/E63277_01/win.121/e63268/entityCodeFirst.htm

Resources