I am creating a Code First Entity Framework to create a database to where I point it to. I have an instance of SQL => DESKTOP-98TG6JE\SQLEXPRESS and another one => DESKTOP-98TG6JE
In my Asp MVC code, my connection string is like so in the Web.config
<connectionStrings>
<add name="MusicStoreDB" connectionString="Data Source=DESKTOP-98TG6JE;Initial Catalog=MusicStoreDB;User ID=sa;Password=myPassword123" providerName="System.Data.SqlClient" />
</connectionStrings>
and in my MusicStoreDB : DbContext,
public MusicStoreDB() : base("MusicStoreDB")
{
}
But when I run the program, it creates a database in the DESKTOP-98TG6JE\SQLEXPRESS named DefaultConnection and on the instance where I want to create the database, no MusicStoreDB database is created.
Image of the created database on the wrong instance
Can you please explain it to me why this is happening? Thank you.
Check you connection string name provided in ApplicationDbContext :
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("MusicStoreDB")
{
}
}
Related
I am using MVC 5 and sql server 2012.I have created DB with name TestDB its doest not contain any table.Now i am trying to use Identity which is default given in AccountController in MVC project. I have change in AccountController "Defaultconnection" to my TestDBEntities connection but i am getting error
System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context. How i can created Identity with exist Database.
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/DAL.TestModel1.csdl|res://*/DAL.TestModel1.ssdl|res://*/DAL.TestModel1.msl;provider=System.Data.SqlClient;provider connection string="data source=xxxxx;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("TestDBEntities", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
As per my understanding, the possible ways to solve your problem is:
1.Cross check that have you added the ApplicationDbContext to the UserStore constructor
Ex: https://stackoverflow.com/a/23894335/3397630
2.Also check that do you have any other connection string in the webconfig file. This may also cause the problem.
Finally if both above points doesn’t work, kindly follow the below article:
http://www.codeguru.com/csharp/.net/net_asp/mvc/securing-asp.net-mvc-applications-with-asp.net-identity.htm
It was really good, I personally used and created a identity tables for my projects without any issues.
In the articles, it was explained each , every points very well and easy understandable.
Hope the above information will be useful , kindly let me know your thoughts or feedbacks
Thanks
Karthik
I've been following this Microsoft Article on implementing a secure web app. It is working fine with the local database. But when I change the connection string to the external database I consistently get an error when trying to interact with the identity tables
AspNetUsers
AspNetRoles
AspNetUserClaims
AspNetUserLogins
AspNetUserRoles
These tables have been re-created in the external Azure db and I followed this walkthrough. The error I get when trying to register is
The entity type ApplicationUser is not part of the model for the current context.
When trying to register it fails on this line of code in the AccountController
var user = await UserManager.FindByNameAsync(model.Email);
I want to take a database first approach as the external db already has pre-existing data. I've looked at several other posts and sites but I've been unable to solve the issue. I've also tried enabling and updating the db with no success through the Package Manager Console.
Thank you in advance!
Here is the ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
//ApplicationDbContext.Equals("", "");
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<proj.Models.Obj1> Obj3 { get; set; }
public System.Data.Entity.DbSet<proj.Models.Obj2> Obj3 { get; set; }
public System.Data.Entity.DbSet<proj.Models.Obj3> Obj3 { get; set; }
}
I don't like answering my own question but here is what resolved my problem.
I had to change the connection string from the one that was generated
<add name="DefaultConnection" connectionString="metadata=res://*/Models.DBName.csdl|res://*/Models.DBName.ssdl|res://*/Models.DBName.msl;provider=System.Data.SqlClient;provider connection string="data source=server;initial catalog=databaseName;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
to this
<add name="DefaultConnection" connectionString="Data Source=server; Initial Catalog=databaseName; User ID=username; Password=password; Connect Timeout=60;" providerName="System.Data.SqlClient" />
I was using the connection string generated during the creation of the EDMX file, database first. Using this connection string was causing my error. I found it a bit deceiving because I was still able to access data from other tables but not the associated identity tables. I hope this will be helpful to anyone experiencing the same issue in the future.
I've created a new C# MVC project in VS2013 and am trying to use their automatically generated user creation function.
It seems in the IdentityModel.cs file, there is a method called ApplicationDbContext as shown below with the "DefaultConnection" string.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Now this seems like its using VS's in built database as shown in the Web.Config file
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-AI-20150321012806.mdf;Initial Catalog=aspnet-AI-20150321012806;Integrated Security=True" providerName="System.Data.SqlClient" />
I'm wanting to use my own database connection string instead while using the in built user creation functions (as the in built user creation seems to have all the fields i need for user creation, and handles password hashing and such), but I can't seem to get the user creation to work when i change the "DefaultConnection" string to my own connection string as defined in the Web.Config file.
<add name="AIEntities" connectionString="metadata=res://*/Models.AIEntities.csdl|res://*/Models.AIEntities.ssdl|res://*/Models.AIEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=PC;initial catalog=AI;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Every time when i try to create a new user, i get the error message:
The entity type ApplicationUser is not part of the model for the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context.
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
What is needed to get the user creation control to work exactly how it would do while changing the connection string?
Well the name of your connection is AIEntities before it was DefaultConnection. In your ApplicationDbContext constructor rename your DefaultConnection to AIEntities
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("AIEntities", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
The ApplicationDBContext then passes that string to connect
Wow this is very interesting, I came across this article:
http://patrickdesjardins.com/blog/the-entity-type-applicationuser-is-not-part-of-the-model-for-the-current-context which seems to describe the problem i'm getting, although their "answer" doesn't work for me (and also for the others who have also commented that it doesn't work for them either).
However after reading "Matt"s comment:
Matt
February 11, 2014 at 03:31
I was having this same problem, and I recall having a similar problem working with SimpleMembership in MVC4.
I’m doing database first development, so I have an EDMX file. Turns out, ASP.NET Identity does not like the connection string that is created when you generate your .edmx model file. If you are using a. EDM connection string in :base(“EDMConnString”) you will most likely have this problem.
I fixed this by creating a standard connection string that pointed to the database where the ASP.NET Identity tables are (in my case the same database), used that connection string in :base, and it worked.
I tried doing the same thing and created a new ConnectionString as follows (basically removed everything that got auto generated when i added a new model):
<add name="AI2" connectionString="data source=PC;integrated security=True;initial catalog=AI;" providerName="System.Data.SqlClient"/>
And under the IdentityModels.cs file, set my connection string to AI2:
public ApplicationDbContext()
: base("AI2", throwIfV1Schema: false)
{
}
And this seems to have solved my problems, it's doing exactly what the template code was doing on its local DB onto my own DB.
I was working at an asp.net MVC project with the IdentityDbContext.
The code for the context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ApplicationDb")
{
}
}
And in my web.config a connectionstring named after the context:
<add name="ApplicationDb" connectionString="Data Source="..." providerName="System.Data.SqlClient" />
Strange thing is when I call the Update-Database command to create the database with Entity Framework, my database is created. So far so good.
But: the authorisation code from Owin is also creating a second upon running the application. This one is named DefaultConnection and is copy from the other one.
So my question: does Identity Framework always need a connection string named "DefaultConnection", even if you point the context to another connectionstring?
In the end I managed to solve this by adding the DefaultConnection connectionstring in web.config so I end up with two connectionstring:
ApplicationDb
DefaultConnection
Is this really the way to go? Because if that's the case it doesn't make much sense to put a custom connectionstring name in the base constructor?!
Btw, I also tried the context like so:
public ApplicationDbContext()
{
}
Which in theory should effectively do the same. But still DefaultConnection is created upon running the app. Doesn't make sense to me.
I'm build my webapi project based on this article: A simple POC using ASP.NET Web API, Entity Framework, Autofac, Cross Domain Support
However, I need to pass a connection string to the DbContext because a user that connects to the webapi can select a different database to work with.
Where and what is that best way to implement this? In the controller, having a separate 'service' or a singleton?
I'm currently building a website that requires multiple databases also. This is the basics (for now). It may not be the best/efficient way, but it does the job so that I can continue working on the site.
Let's say you have this connection and everything there is correct, except the database name can change.
<add name="MyDbContext" connectionString="Server=SomeConnection;Database=SomeDatabase;"providerName="System.Data.SqlClient" />
You can create a connection string on the fly with this
public MyDbContext CreateDbContext(string databaseName)
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString); // Gets the default connection
sqlBuilder.InitialCatalog = databaseName; // Update the database name
return new MyDbContext(sqlBuilder.ToString());
}
Also, unless you want to automatically create a database if it doesn't exist, possibly from incorrect database name, you need to set the initializer. Simply pass the initializer null to prevent ef from automatically creating one. I set this in the constructor of MyDbContext
public class MyDbContext : DbContext
{
/* some other constructors */
public MyDbContext(string nameOrConnectionString, bool createDb)
: base(nameOrConnectionString)
{
if(!createdDb)
{
System.Data.Entity.Database.SetInitializer<MyDbContext>(null);
}
}
}
One way would be to have multiple ConnectionStrings in your web config. You could then select which ConnectionString to use depending on a parameter passed to your webapi:
In your web config:
<connectionStrings>
<add name="dataBase1" connectionString="/*db info here*/" providerName="System.Data.SqlClient" />
<add name="dataBase2" connectionString="/*db info here*/" providerName="System.Data.SqlClient" />
</connectionStrings>
Then in your code:
public someobject GetData(/*arguments*/, string dbType)
{
var connectionString = dbType == 'dataBase1'
? ConfigurationManager.ConnectionString['dataBase1'].toString()
: ConfigurationManager.ConnectionString['dataBase2'].toString()
/*then pass connectionString to dbContext*/
var dbContext = new DbContext(connectionString);
}