I changed my connection string when starting a new mvc project because I needed to use some info out of an existing database. Now I get a "Invalid object name 'dbo.AspNetUsers' when I try to load the startup page. A quick google search says the issue happens because you are connecting to an existing database using asp.net users. Still, this should not occur since I am not using code first migrations, right? What is more, I am using Active Directory to authenticate my users instead of individual user accounts.
In addition, the AspNetUserstable does not exist in the database I am calling in the web.config:
Due to the fact that I am not using the UserStore or the ApplicationUser provided by the Individual User Accounts defaults I needed to change this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
to
public class ApplicationDbContext : DbContext
Optionally If you are using Code First Migrations you could add the initial migrations, remove all of the sql code from the up and down methods, and finally update the database. Even though the tables will still not exist it seems to satisfy the compiler and your project as the error goes away and the page loads as expected.
Related
I'm trying to add Identity to an existing and working MVC project.
When used this command Add-Migration CreateIdentitySchema I got error message: 'More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.' and I chose the existing DB context that I have previously created for the main functionality of the application and now it shows 'There is already an object named 'ExpenseReport' in the database.' so it's trying to recreate my initial model.
Should I have a separate DB Context for Identity and if yes how to connect user to data from the other context?
So, i think you can use several DbContexts with different connections (just need to write it in your Startup class) or you need to use pattern "DbContext Factory". You can read more here .
Hope it will help you.
I'm a bit new to code-first approach but I used Database first approach before using entity framework, now I want to work with code first instead and its kinda a habit.
I started creating models and its all good, then enabled migrations and add-migration as well and all works well, but when I run Update-Database command I get an error.
Hence I want to create a database with code-first using credentials, after a lot of research I didn't find a solution and mostly tutorials use "Trusted Connection".
What I use
App.Config
<connectionStrings>
<add name="CodeFirst" connectionString="Server=.\SQLEXPRESS;Database=CodeFirst;User ID=anyuser;Password=anypassword;"
providerName="System.Data.SqlClient" />
</connectionStrings>
DbContext Class
public class CodeFirstContext : DbContext
{
public CodeFirstContext() : base("name=CodeFirst")
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
The Error I get
Login failed for user 'anyuser'.
The question is I did something wrong ? or using credentials can't be done using code-first approach ?
Thanks in advance
OP:
I want to create a database with code-first using credentials,
...and:
after a lot of research I didn't find a solution and mostly tutorials use "Trusted Connection".
Therein lies the problem with code-first approaches when deploying to a new database using a specific login - it's a chicken and egg because:
the database doesn't yet exist
the connection string is requesting an explicit login
the login does not yet exist in say SQL
because the database doesn't exist
OP's config:
<connectionStrings>
<add name="CodeFirst"
connectionString="Server=.\SQLEXPRESS;Database=CodeFirst;User ID=anyuser;Password=anypassword;"
... />
</connectionStrings>
So what's the solution?
Use Integrated Security: this allows you to create the database from scratch from code. However any other logins you may need might have to be created later. However, DB-speaking, it's a bit of a bad practice because you should get into the habbit of having one account for deployment (with just enough rights for deployment) and another for general app access (and no rights for deployment)
Create Login First: this allows you to use your specified login however you most likely will need to create a blank database first from SQL before you can create the login. Code-first purists may not like this idea.
The latter does follow DACPAC best practices you should already be familiar with from your time in database-first. Just like how a DACPAC shouldn't be deploying logins and adjusting security neither should code-first. Afterall at the end of the day, databases don't care about whether you use code-first or database-first (under the hood, both probably employ some form of encasulated scripting) but your DB Admin might raise an eyebrow depending on how security is being used.
Are database-first approaches better?
In the theme of don't do that, try this instead, code-first tries to do everything via code and whilst a noble pursuit perhaps isn't realistic. Some things like attempting to create logins perhaps isn't possible as mentioned above.
Meanwhile database-first schema changes are carried out by deploying DACPACs from the database side. Authentication is via the login used to get into SSMS (for example) in the first place. DACPAC deployment doesn't require code, .NET or otherwise.
DACPACs can create and/modify database security including logins but is generally frowned upon.
You might want to re-think code-first. Code-first and EF Migrations hasn't really succeeded as a concept in the real world where you have staged CD environments such as DEV; TEST; UAT and PROD.
I see so many developers using code-first only for deploying to their local database. Once there, they use different means to deploy the changes to other computers including TEST and PROD whether it's TSQL scripts or database backup.
It just seems to be so much effort for something that doesn't even complete the race.
I went to upgrade our ASP.NET Web Forms solution from Identity 1.x to Identity 2.0. I updated the three Identity 2.0 packages. I then went to work on implementing Password Reset, etc. I didn't realize I had to Update the Database. That migration failed because the tables were in the wrong context. We decided to start over. We deleted the tables but they are not getting recreated when I access the Login page. How do I get these tables regenerated or should I create them manually?
Try disabling the schema consistency. This is one time thing that needs to happen when you upgrade asp.net identity from version 1.0 to 2.0.
public ApplicationDbContext() : base("MyConnection", throwIfV1Schema:false)
Notice I added throwIfV1Schema:false as a second parameter. Compile it, try to log in so the DB gets updated, do the migrations if needed and then you can remove it.
tl;dr: Identity seems to require that LazyLoading NOT be disabled; is this true, and what is the cleanest workaround?
I did some basic A-B testing on a simple C# ASP.NET 4.5.1 MVC-5 web application using EntityFramework 6.0.2, Identity EntityFramework 1.0.0, and Identity Owin 1.0.0 and it appears that Owin requires that lazy loading is NOT disabled in the ApplicationContext constructor.
To replicate the issue just make a quick MVC app using Visual Studio 2013, use the MVC template, leave everything at the defaults except uncomment the line: 'app.UseGoogleAuthentication();' in App_Start/Startup.Auth.cs. Run the app and use Google to login, complete the abbreviated registration page it takes you to and go to account/manage. You should see 2 buttons for Google at the bottom. Stop the app.
Now go to ApplicationContext.cs and change the constructor as shown in this code snippet:
public ApplicationContext() : base("DefaultConnection") { } //Works!
public ApplicationContext() : base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
} //Does not work
Retry the test. Only 1 Google button should be visible. With LazyLoadingEnabled = false the User Roles, Logins (poss Claims also) aren't loaded.
My theory is that this is a Microsoft oversight/'future feature' as Identity EntityFramework and Identity Owin are both version 1.0.0.
My question is, can this test be confirmed, and what is the cleanest work around?
For my purposes I will just use .ToList() and other methods for forcing EagerLoading when I want to use it. I don't truly need LazyLoading disabled, it's just a safer way to code if you want to always use eager loading. i.e. you miss one spot, it makes it to production, and you have a nice bug where in some View you are iterating through a Model and for Model.x.y y == null and the database connection has been disposed.
Let's not get into Identity vs. other (more robust) methods, or:
using (DatabaseContext) { //Database query }
or calling dispose on every method vs letting the connection be disposed automatically. This is a scenario where you have to use Identity Owin, and dispose of all database calls ASAP. There ought to be something I'm missing, or maybe Identity really is just that incomplete right now.
Yes this was a bug we have fixed in the 2.0.0-alpha1 release. With lazyLoading explicitly disabled prior, EF would not load the associated user entities automatically (logins/claims/roles)
I am still a relatively inexperience with Visual Studios and C# so please let me know if necessary information has not been provided or I am unclear in my description.
I have an MVC 4 project in Visual Studio 2010 Web Developer Express and I am attempting to set up basic Forms Authentication. I have used the ASP.NET Configuration Manager to set up a couple test users and roles. The Configuration Manager has also created the ASPNETDB.MDF database in my App_data folder which has been included in the project.
I am currently using the generated AccountController and Account views.
Whenever I attempt to access a HTTPGET or HTTPPOST method with which has the [Authorize] attribute, a TargetInvocationException is thrown from the following method in the InitializeSimpleMembershipAttribute class:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
When viewing the details of the exception, the inner exception states that "The ASP.NET Simple Membership Database could not be initialized."
The inner exception of the above inner exception states that it "Could not find the conceptual model type for" a given model.
The model that was not found belongs to an ADO.Net [.edmx] file which is generated from a database. The model that it cannot find is alphabetically the first table/class in the database, so it likely also applies for every class from that database.
I am not sure if it is important, but I use a database separate from the ASPNETDB.MDF to store information enter on the website.
I do not understand why the LazyInitializer.EnsureInitialized() method may be causing this problem.
Have you checked the connection string used by WebSecurity.InitializeDatabaseConnection in Global.asax.cs Application_Start() - this could potentially cause the issue.
If the named connections string is correct are you sure the dbContext connection string is correct:
public SomeContext(): base("MyConnectionStringName")
{
}