How to use Membership provider with EF Code First? - asp.net

I have models based on EF Code First and I want to use them with the default MembershipProvider, but I don't know how to write the model correctly, so it won't erase all my data on recreating the tables when there were changes made to the model.

Have a look at this project
http://codefirstmembership.codeplex.com/
It has entity classes for users and roles, as well as a roleprovider and membershipprovider implementation. If you include the users and roles in your datacontext class the tables will be created in your database.

Your question has two parts.
How to use asp.net membership API with EF code first?
How to preserve existing data when model changes?
as for How to preserve existing data when model changes, as far as with EF 4.0/ asp.net mvc 3, database migrations are not yet supported. You will have to move to asp.net mvc 4.0/ EF 4.3 where database migrations are supported or use similar alternatives , but its still beta release.
asp.net mvc 4.0 database migration in scott gu's blog
Now coming to the point on how to use asp.net membership provider with EF code first. There are couple of challenges :
We cannot/should not do an join with asp.net membership provider tables. Its not recommended, so my suggestion will be to create a "adapter class" for asp.net membership provider classes. For ex :
public class UserAdapter
{
// all user related attributes. Not stored in membership schema, but your schema
public string UserProxyName;
// some attributes stored in membership schema
[NotMapped]
public string Email {
get
{
Membership.GetUser(UserProxyName).Email;
}
}
// some attributes stored in membership schema and not in your schema
[NotMapped]
public string[] UserRoles
{
get
{
return Roles.GetRolesForUser(UserProxyName);
}
}
}
Now for updating information , you may write some functions in Model itself, however i would suggest create a UserRepository with repository design pattern to handle user CRUD operations.
Second challenge is how to create the database on first run. As seeding becomes an issue, if you want to seed user information then seperately running aspnet_regsql is not efficient as membership schema is expected before the seeding happens. I came across this nice article , with some fine tuning it worked for me :
asp.net membership and EF

Currently (EF 4.1 CTP) EF Code First doesn't have that option. It always drops a table if you made changes to model.
Update:
EF 4.1 RTM allows you to create a custom database initializer and specify creation of db objects and data seeding.

If you are using SQL Server, then check this :
http://www.paragm.com/ef-v4-1-code-first-and-asp-net-membership-service/

There is also my library which basically allows you to define how almost everything should be configured including: key type, where the your context object is, and where your user/role entities are located. Extendable using abstract base classes or interfaces. Also works quite well out of the box with repository pattern / unit of work / IoC Containers.
Source: https://github.com/holyprin/holyprin.web.security
NuGet: https://nuget.org/packages/Holyprin.Web.Security

In my DbContext.cs file I have a Seed function where I call the ApplicationServices.InstallServices() to install the ASP.NET Membership to my database. Now everytime my initializer drop the database it recreates ASP.NET Membership schema again.
public class PanelInitializer : DropCreateDatabaseAlways<PanelContext>
{
protected override void Seed(PanelContext context)
{
//Install ASP.NET Membership
ApplicationServices.InstallServices(SqlFeatures.Membership | SqlFeatures.RoleManager);
new List<Panel>
{
The ApplicationServices class
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Management;
namespace Lansw.Panels.DataAccess.Contexts
{
public class ApplicationServices
{
readonly static string DefaultConnectionString = ConfigurationManager.AppSettings["DefaultConnectionString"];
readonly static string ConnectionString = ConfigurationManager.ConnectionStrings[DefaultConnectionString].ConnectionString;
readonly static SqlConnectionStringBuilder MyBuilder = new SqlConnectionStringBuilder(ConnectionString);
public static void InstallServices(SqlFeatures sqlFeatures)
{
SqlServices.Install(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
}
public static void UninstallServices(SqlFeatures sqlFeatures)
{
SqlServices.Uninstall(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
}
}
}
Thanks to #ImarSpaanjaars http://imar.spaanjaars.com/563/using-entity-framework-code-first-and-aspnet-membership-together.

Related

Optimize connection to SQLite DB using EF Core in UWP app

I'm currently working on a C# UWP application that runs on Windows 10 IoT Core OS on an ARM processor. For this application, I am using a SQLite DB for my persistence, with Entity Framework Core as my ORM.
I have created my own DBContext and call the Migrate function on startup which creates my DB. I can also successfully create a DBContext instance in my main logic which can successfully read/write data using the model. All good so far.
However, I've noticed that the performance of creating a DbContext for each interaction with the DB is painfully slow. Although I can guarantee that only my application is accessing the database (I'm running on custom hardware with a controlled software environment), I do have multiple threads in my application that need to access the database via the DbContext.
I need to find a way to optimize the connection to my SQLite DB in a way that is thread safe in my application. As I mentioned before, I don't have to worry about any external applications.
At first, I tried to create a SqliteConnection object externally and then pass it in to each DbContext that I create:
_connection = new SqliteConnection(#"Data Source=main.db");
... and then make that available to my DbContext and use in in the OnConfiguring override:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(_connection);
}
... and then use the DbContext in my application like this:
using (var db = new MyDbContext())
{
var data = new MyData { Timestamp = DateTime.UtcNow, Data = "123" };
db.MyData.Add(data);
db.SaveChanges();
}
// Example data read
MyDataListView.ItemsSource = db.MyData.ToList();
Taking the above approach, I noticed that the connection is closed down automatically when the DbContext is disposed, regardless of the fact that the connection was created externally. So this ends up throwing an exception the second time I create a DbContext with the connection.
Secondly, I tried to create a single DbContext once statically and share it across my entire application. So instead of creating the DbContext in a using statement as above, I tried the following:
// Where Context property returns a singleton instance of MyDbContext
var db = MyDbContextFactory.Context;
var data = new MyData { Timestamp = DateTime.UtcNow, Data = "123" };
db.MyData.Add(data);
db.SaveChanges();
This offers me the performance improvements I hoped for but I quickly realized that this is not thread safe and wider reading has confirmed that I shouldn't do this.
So does anyone have any advice on how to improve the performance when accessing SQLite DB in my case with EF Core and a multi-threaded UWP application? Many thanks in advance.
Secondly, I tried to create a single DbContext once statically and share it across my entire application. So instead of creating the DbContext in a using statement as above, I tried the following...This offers me the performance improvements I hoped for but I quickly realized that this is not thread safe and wider reading has confirmed that I shouldn't do this.
I don't know why we shouldn't do this. Maybe you can share something about what you read. But I think, you can make the DBContext object global and static and when you want to do CRUD, you can do it in main thread like this:
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//App.BloggingDB is the static global DBContext defined in App class
var blog = new Blog { Url = NewBlogUrl.Text };
App.BloggingDB.Add(blog);
App.BloggingDB.SaveChanges();
});
But do dispose the DBContext at a proper time as it won't automatically get disposed.

Extending current User class to handle Identity

We are using forms authentication on our ASP.NET website but are wanting to upgrade to the new Identity Provider. Currently we are using the database first approach and are ultimately wanting to just extend our current User table (not aspnet_users) to use the new identity format. We are using StructureMap to inject our context into our business logic classes. For instance our User service currently has this as its constructor:
private readonly SiteModelContainer _context;
public UserService(SiteModelContainer context)
{
this._context = context;
}
And in our IoC registry we have this:
var ecsbuilder = new EntityConnectionStringBuilder();
ecsbuilder.Provider = "System.Data.SqlClient";
ecsbuilder.ProviderConnectionString = #"data source=***;initial catalog=***;persist security info=True;User ID=***;Password=***;multipleactiveresultsets=True;App=EntityFramework";
ecsbuilder.Metadata = #"res://*/Data.***.csdl|res://*/Data.***.ssdl|res://*/Data.***.msl";
string connectionString = ecsbuilder.ToString();
For<SiteModelContainer>().Use<SiteModelContainer>().Ctor<string>("connectionString").Is(connectionString);
For<IUserService>().Use<UserService>();
...all the rest of our services
We are also using database first with EDMX and entity framework. Previously we just used ASP.NET authentication as it came out the box and had a separate user table to store profile information, but would like to have everything working off one users class instead.
1)Is it possible to extend our userservice to handle everything related to using Identity? So that Identity uses the same context that we inject into our classes? If so, I am unable to find any articles about it?
2) Are we able to extend our User object if it is created in the EDMX file?
Thanks
I have migrated 2 fairly large projects from MembershipProvider into Asp.Net Identity and both of the times I ended up rewriting most parts of the user-management and everything that touched user. A fairly chunky rewrites.
What you ask for is possible, but hard and very time consuming. You may start from this question - the OP have got his db-first project running with identity. And we had a discussion in comments with some links that might help you.

Extending SimpleMembership to support Multi-Tenancy

I have a multi-tenant app that's using SimpleMembership. Each User in my system is linked to one or more Tenants. I've extended Users simply by adding the required fields to the User model (and Tenants):
public class User{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public virtual ICollection<Tenant> Tenants { get; set; }
}
This is working great. But now I'd like to have Roles be tenant-specific, where some role types MUST have a TenantId defined. This isn't as simple as the user problem, as each of the following will be affected:
Adding Roles, Checking Roles:
if (!Roles.Privider.RoleExists("Moderator")) // I now want to include TenantId here
{
roles.CreateRole("Moderator"); // and here
}
Assigning/Checking Roles Using Provider:
if (!Roles.IsUserInRole("Admin", "SystemAdministrator")) // and here
{
roles.AddUsersToRoles(new[] { "Admin" }, new[] { "SystemAdministrator" }); // and here
}
Role Attributes:
[System.Web.Http.Authorize(Roles = "SystemAdministrator")]
public class AdminApiController : BaseApiController
User.IsInRole:
if (User.IsInRole("Administrator"))
{
I'm pretty new to ASP.NET, so I'm not sure where to begin here. Should I be overriding the SimpleMembership Role Provider somehow, or should I look into writing my own Role columns, classes, etc? It would feel wrong to hand-code anything around authentication... Any pointers around this would be much appreciated.
The first problem I see with implementing this is the use of the AuthorizeAttribute because attributes require constant information defined at compile time. With your tenant-based approach I would think which tenant to check would need to be determined during run-time. So the first thing I would do is take the approach described in this article on Decoupling You Security Model From The Application Model With SimpleMembership. Now you decorate this attribute with a resource and operation (which will be static) and you can configure what roles are assigned to the resource/operation at run-time in the database. This gives you a lot more flexibility in designing your security model as you add tenants.
Changing the database model for anything but the UserProfile table in SimpleMembership is not possible (See this QA). So adding tenant ID's to roles is not possible without writing your own membership provider. If you want to stick with using SimpleMembership one solution is to handle this in your naming convention for roles, where you include the role name and tenant name or ID. For example, if you have two tenants that have the admin role you would have two roles that are named "Administrator_Tenant1" and "Administrator_Tenant2". If you need to display this to any users that assign roles you could clean up the name by stripping out the tenant ID/Name for viewing.
If this is a new project and you are not tied to SimpleMembership you may want to look at using at Microsoft's latest membership system called ASP.NET Identity. This membership system replaces SimpleMembership in MVC 5. ASP.NET Identity was built to be easily customized and you should be able to change the role model. There is an article on customizing ASP.NET Identity here.

EF Code First creates a reference table instead of a federated table in SQL Azure Federation

I'm trying to connect to SQL Azure Federation using Entity Framework code first approach. When I attempt to write to a federated table, EF throws an error saying "There is already an object named [pluralized table name] in the database"
I get this error because I created the federated tables before running the application code. If I delete the tables, then EF will create them for me without throwing an exception, but this time they won't be federated. They will be reference tables instead.
How do I solve this problem? Could I prevent EF code first from attempting to create a table?
Found the answer myself.
class CreateDatabaseIfNotExists<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
public void InitializeDatabase(TContext context)
{
}
}
And I call it in my DBContext class like so:
static EVENTContext()
{
Database.SetInitializer(new CreateDatabaseIfNotExists<EVENTContext>());
}

UnitOfWork + Repository patterns and Entity Framework impersonation

I have used UnitOfWork and Repository patterns in my application with EF.
Actually my design provides that the UnitOfWork would create the ObjectContext class and inject inside the Repository concrete class. For example:
UnitOfWork.cs (initialization)
public DefaultUnitOfWork() {
if (_context == null) {
_context = new MyDataContext(ConfigSingleton.GetInstance().ConnectionString);
}
}
UnitOfWork.cs (getting a repository instance)
public CustomerRepository Customers {
get {
if (_customers == null) {
_customers = new CustomerRepository(_context);
}
return _customers;
}
}
This way the Repository classes have an already defined ObjectContext class and they can use it's methods to retrieve and update data.
This works nice.
Now I need to execute my queries impersonating the Application Pool Identity so I have decided to wrap the code in the constructor of the UnitOfWork within the impersonation.
Unfortunately this does not work because the ObjectContext is then passed to the Repository constructor and used later when a client of the repository calls, for example, FindAll().
I have experienced that the real connection to the database is made right before doing the query by Entity Framework and not exactly when I am creating the ObjectContext itself.
How can I solve this problem?
You could use one or more ObjectContext Factories (to create ObjectContexts), using different creation criteria, such as Connection String, for example. Your UnitOfWork could leverage a factory to get its Context and so could the Repository, but I think you've missed the point of UnitOfWork if it is leveraging a different ObjectContext than your Repository.
A UnitOfWork should consist of one or more operations that should be completed together, which could easily leverage multiple repositories. If the repositories have their own ObjectContexts separate from the UnitOfWork, I don't see how committing the UnitOfWork will achieve it's purpose.
I think either I've misinterpreted your question completely or you've left out some pertinent details. Good Luck!

Resources