ASP.NET Identity 2.0 DB First Approach: Adding new Columns - asp.net-mvc

I am trying to use ASP.NET Identity 2.0 with existing database.
I have created an MVC project (which uses Individual Account Authentication), then I registered for a use in order to create the DB.
Then:
I created scripts for the necessary tables and added them to my own DB
I added ADO.NET Entity Data Model (database first) which include my tables plus identity tables.
I ran the application and registered for a user, everything is going fine.
Now, I need to add a relation to AspNetUser table.
I added the Column LocationId with the relationship in DB.
I Added the following to the Application User Class:
public virtual Region Region { get; set; }
Then, I updated my Model and run the application, when I tried to register for new user, I got the following error:
AspNet UserLogin: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNet UserLogin' that has no keys defined.
How is it possible to continue using DB First Approach in this scenario?

Identity uses Code First approach for making Identity System make customization as more as possible and you are using DB first approach for your common data access. So there are 2 contexts, one is for your data and other is for you Identity. You need to write Identity classes and make a code first migration of Identity context class by typing in the Package Manager Console as:
`Enable-Migrations -ContextNameType [Your_Identity_Context]
This will enable code first migrations just for your Identity context type. If you want to add region property in your user table, then in 'ApplicationUser' (or any class derived from IdentityUser) add the required region property and then apply the migrations to update the user table in the database.
Generating SQL script and applying to the database is not a good approach.

Related

Add column to database without defining it in model with Entity Framework

Is it possible to add a column (or execute some SQL) to a table when Entity Framework is instantiating a new database, without defining it in the Model used in DbSet ?
Iam building a prototype for a SaaS application with Entity Framework and Elastic Scale Client, and want to use Row Level Security, for that a need a column to identify my tenants. So i figured it would be nice if I could use just the EF initializer to add this column, when adding new tenants to the system.
As noted in the documentation here, you can execute sql when you have the DBContext.
From the docs:
using (var context = new BloggingContext())
{
context.Database.ExecuteSqlCommand(
"UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}
You could use this to modify the structure without having the actual structure defined in EF.

How to inherit from IdentityUser in entity framework designer

I have an asp.net mvc project that uses asp.net Identity to authenticate users. The database has been designed in entity framework designer.
There is a table named "Farmers" and I want to allow each farmer to login to the application. As I know in order to achieve this, the farmer must inherit from IdentityUser, but how can I do this in entity framework designer?
what is your mvc version??
in mvc5 this is a good response
http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx
for this way u can mixed the two tables.
the other way is create an relationship between the two tables an use
User.Identity.Name or
User.Identity.GetHashCode
an use this to obtain the values of connected user
After a lot of hours of research I figured out that inherit from ApplicationUser or IdentityUser is not possible using the Entity Framework Designer.
My solution is to create a Code First Model from the existing database and then inherit from ApplicationUser.
As far as I know you can't really do that and I would argue that you shouldn't even try to do that even if you could.
By inheriting from IdentityUser you are saying that the Farmer can be described by properties like SecurityStamp, Roles or PasswordHash (inherited from IdentityUser) which does not make that much sense from a design point of view.
If what you are looking for is having a direct association between a user and a farmer you could simply add a required UserId property in you Farmer model. So whenever you create a new UserIdentity instance you also create a new Farmer instance as well with the UserId set to be the Id property of the newly created UserIdentity.

Identity 2.0. How to relate a user table in my EF context to Identity AspNetUsers table

I am using a boiler-plate VS2013 generated project (Code First, Migrations).
I wish to take the easy route and use all the built-in Identity API for handling of authentication and accounts (register, login all that).
Yet I wish to have a separate user table (let’s call it AppUser) with its own attributes that is not part of Identity because I am implementing my own domain with other relationships (Company => user hierarchy, Documents, etc) this is all admin’d outside of Identity by my custom pages. The AspNetUser would have already registered his account prior to my custom pages wiring him in.
My issue is how do I setup a relationship in the context from AppUser to AspNetUsers.
I thought this would be pretty simple but I am lost.
The only thing I can come up with is to have AppUser have a string called AspNetUser_ID that I would manually join to the AspNetUser table.
This seems pretty brittle and I would prefer it could have a FK constraint.
The other thing I cannot figure out is how to get AspNetUser in my DBContext so it is accessible.
Any help would be great.
Since you're using the boilerplate template, you should be able to find a class file named IdentityModels.cs in the Models folder. There, you can find the ApplicationUser class, to which you can add all the extra properties you want, as with any other Code First entity. This is the entity that maps to the AspNetUsers table. Here you could just add your AppUser class as a navigation property, or maybe, to keep things simple, add the properties from AppUser to ApplicationUser, so you only have one ***User entity to deal with.

How can I create and use views using EF6 Code First?

Is there actually any official strategy for creating and using views with EF6.1 Code First? I can reverse the database into Code First and get tables not views. I can import the database into Model First and get views and then do Generate DB from Model and my edmx is modified and the views are converted to tables. MSFT seems to have all but abandoned Model First, and the new Update 2 seems to have reverse engineering for Code First so I feel forced to convert to Code First but has the EF team given support for any reasonable approach to using views or stored Procedures in Code First? After all CF is supposed to create the DB but what - are you no longer supposed to use either of these SQL Server features in a .NET EF application?
For starters you can use views and stored procedures that are already created in the database. For views you don't have to do any mapping if you create a code like this:
public TestContext : DbContext
{
public DbSet<User> AdminUsers { get; set; }
}
And you have a view in the database named dbo.AdminUsers and it can be mapped to the class User (contains all required properties with the same name as the property).
For stored procedures you can use the SqlQuery function either through the Database property of the DbContext such as:
var userActivityReport = context.Database.SqlQuery<UserActivityReport>(
"dbo.GetUserActivityReport #p0, #p1", startDate, endDate);
Or through the SqlQuery function of the DbSet class:
var newUsers = context.Users.SqlQuery("dbo.GetNewUsers #p0", count);
If you want to create, modify or delete views and stored procedures via Entity Framework you can either use custom migration operations see http://dolinkamark.wordpress.com/2014/05/03/creating-a-custom-migration-operation-in-entity-framework/
For event better integration you can use the Public mapping API with a library provided by a community member: https://codefirstfunctions.codeplex.com/

How to autoCreateTables along with SimpleMembership tables in ASP.NET MVC

Today, I created a new ASP.NET MVC 4 project - Internet application.
With all the files that comes in the solution in the Account Controller I saw an attribute called [InitializeSimpleMembership]
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{}
and by only providing a proper db connectionstring property in the web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;
Initial Catalog=demo;
User ID=test;Password=test;" providerName="System.Data.SqlClient" />
and when the application runs, it checks if the available database exists or not and if not creates one and adds few memebership tables to it also. I must say I was very very impressed with the new MVC 4 - Internet app template.
Which brings me to my question :
I liked the idea of creating database and executing script from the application. I wanted to know how to add more tables to this.
For example : In the InitializeSimpleMembershipAttribute.cs file it check if a database is present, if not it creates it using the credentials present in the web.config and also adds the following tables to it.
UserProfile
webpages_Membership
webpages_OAuthMembership
webpages_Roles
webpages_UsersInRoles
what changes do I have to make to have my other tables to be added along with this ?
If this is possible, the idea of keeping sql scripts and executing them on each clean deploy can be avoided. I am working on a self-host MVC app ( It's Open-source, soon to come on Codeplex ;) ) so this will really be good for people who want to use my app without getting their hands dirty in SQL scripts.
Please can some one let me know if this is even possible. Thanks
There are two distinct parts to the tables being created:
The UserProfile table is created by adding the attribute [Table("UserProfile")] before the model in Models/AccountModels.cs (remember to add it as a DbSet to your context as well).
The 'webpages_' tables are created by the WebSecurity.InitializeDatabaseConnection call in Filters/InitializeSimpleMembershipAttribute.cs called by adding the [InitializeSimpleMembership] in Controllers/AccountController.cs. These are 'internal' tables required by the SimpleMembershipProvider and you would not typically want to alter them.
This is called the CodeFirst method of the EntityFramework (your other options are ModelFirst and DbFirst). To have your own POCOs/models auto created you would want to add the Table("TableName") attribute similar to UserProfile above.
Refer to the Entity Framework Website for full walkthroughs of the CodeFirst approach (and much much more).
http://msdn.microsoft.com/en-us/data/ef.aspx

Resources