Creating authentication using own dbcontext

516 Views Asked by At

I want to create an owin authentication using my own external sql database instead of the base asp context. I can create an edmx model from the database but i dont know how to use it to identify the users.

When i change the base Database connection used by ApplicationUser to my own one i get this exception.

I have already created at least 30 projects to test the solutions i found on google but none of them was worked for me.

1

There are 1 best solutions below

0
On BEST ANSWER

[SOLUTION]

The solution is much more easier than i thougth..

All i had to do was inheriting my User table from IdentityUser (AspNetUser is my own table)

public partial class AspNetUser : IdentityUser

and using my custom connectionstring's name (BCTSDb) instead of DefaultConnection in IdentityModels.cs.

public ApplicationDbContext()
        : base("BCTSDb", throwIfV1Schema: false)

This is codefirst from database, database first is not working with this solution (i dont know why).

This solved the FIRST problem. After this i couldn't scaffold any controllers with views because of missing keys and ambiguous references.

[WHATTODO]

1. Ambiguous references

In my AspNetUser.cs class i made all ORIGINAL attributes override: for example UserName:

public override string UserName { get; set; }

Its possible that this is not necessary, i haven't tried without this, maybe this solve the ambiguous references between my dbcontext and ApplicationDbContext.

2. Missing keys

I dont know where i left my keys but there is the solution:

At the end of my OnModelCreating function (in my dbcontext) i wrote the following lines:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // your table operations, references
        // ...

        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });

        base.OnModelCreating(modelBuilder);
    }

After this i could do anything i want.