简体   繁体   中英

Entity Framework (existing database)

I am completely new to ASP.NET MVC and don't know what is what at this point. I have spent many hours trying to figure out what I think should be quite simple and searched the web quite a bit!

I have created an ASP.NET MVC project which prepopulated things such as the Login and Register page.

I got Entity Framework to connect/use my existing DB and wanted to register a user(ie insert a new user into the DB). Using the code that was pre-populated worked, but inserted into an "internal DB" which is not what I wanted, but using the async await did not work when trying to insert into my existing DB (gave an error in the lines of Model.User can not be converted to Model.DB.User or something along those lines), so I am now doing it synchronously but quite liked the validations it did (ie checking if user already existed etc., which I have now coded myself).

(sorry for all the typing)

Now I want to log in, and this is the code :

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent:false, shouldLockout: false);

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        //case SignInStatus.RequiresVerification:
        //    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
} 

But this fails. I dug a little deeper and its searching in the [AspNetUsers] table? How do I get it to search in MY Employee table in my Existing DB ? I like the validations and based on what I read what async and await does, id like to keep using it.

Ultimately my question is how can I for example get the above code to read from my entity Framework(existing DB) and not from this "internal DB" ?

I hope this makes sense.

Thanks for the help.

EDIT:

Below is the LoginModelView class being used :

public class LoginViewModel
  {
      public string FirstName { get; set; }
      public string Surname { get; set; }

      public string Email { get; set; }

      [Required]
      [Display(Name = "User Name")]
      public string UserName { get; set; }

      [Required]
      [DataType(DataType.Password)]
      [Display(Name = "Password")]
      public string Password { get; set; }
      public DateTime LastLoggedIn { get; set; }
      public bool isLockedOut { get; set; }
      public bool isAuthorized { get; set; }
      public bool isActive { get; set; }
  }

My Employee table consists of the following columns (if this even matters):

PK_UserID, Firstname, Surname, Email, UserName, Password, LastLoggedIn, isLockedOut, isAuthorized, isActive

What you are trying to use is called ASP.NET Identity . It is a framework for user management, authentication, authorization, etc. By default it uses Entity Framework to access a database (will create it if it does not exist) but the specific implementation will require specific tables. You have several choices but I am afraid there is no easy one.

  1. Let ASP.NET Identity create its tables into a new database, script them, put them in your database, change the connection string to point to your database and you have a login system that is in your database. The problem here is that it will NOT use your tables. If your database is new and you can control the design you can change these tables (and the corresponding classes like User) to store the data you want (for example you can add EmployeeNumber to the AspNetUsers table). The downside is that you can't just use your Employee table. You have to accept the predefined tables as part of your model. Now it is debatable if it is a good idea to use the Employee table for login to begin with but still...

  2. This is probably the hardest solution. Implement your own provider for ASP.NET Identity. If you give the identity system a way to do certain operations it will work. However this is a lot of work and you may need a lot of fields from the original tables anyway. Here is more information on implementing providers . I don't think this is a good solution for your case. This is good if you have different storage for your user data not good if you simply dislike the user requirements. Also you will have to write code for many of the checks that you liked.

  3. Do not use ASP.NET Identity. You can use lower level authentication mechanism (in fact ASP.NET Identity uses it) to create a secure encrypted cookie and write your own queries to the database to determine if the user should be logged in successfully. Information on how to use OWIN authentication . In this case you can implement whatever logic you want but you have to do it yourself. No checks performed for you and you have to make sure you hash the passwords properly and so on. You can still use Entity Framework to do those queries to the database. You can write async queries just like the ASP.NET Identity provider does. This is fully supported by EF. If you do not want the identity tables into your database this is probably your best bet.

Sadly none of these is perfect and easy fit for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM