Witam. Tworząc aplikację webową dodałem sobie obsługę rejestracji i logowania za pomocą gotowego modułu AspNet.Identity. Wszystko działa lecz przy rejestracji użytkowników niektóre dane jak email, hasło itp dodają się prawidłowo do wygenerowanej tabeli AspNetUsers ale nie ma w niej kolumn utworzonych w moim modelu Users (ulica, imie, nazwisko itd. ). W bazie oprócz wygenerowanej tabeli AspNetUsers mam swoją tabelę Users z moimi kolumnami i to tam powstają nowe(puste) wiersze przy rejestracji. Moja tabela Users już w bazie była stworzona przed dodaniem AspNet.Identity. Podsumowując niektóre dane, te potrzebne do logowania zapisują się w wygenerowanej tabeli a inne, te niepotrzebne jak imie, nazwisko w mojej tabeli a to chyba nie jest zbyt dobre podejście ?
Próbowałem usunąć tabelę Users z bazy ale wtedy wywala błąd, że brak jej w bazie a chciałbym je obie scalić do tej wygenerowanej.
Enities (Context)
namespace BooksDAL.EF
{
public class BooksEntities : IdentityDbContext<ApplicationUser>
{
// Your context has been configured to use a 'BooksEntities' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'BooksDAL.EF.BooksEntities' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'BooksEntities'
// connection string in the application configuration file.
public BooksEntities()
: base("name=BooksConnection")
{
}
public static BooksEntities Create()
{
return new BooksEntities();
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
//public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<OrderPosition> OrderPosition { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<CartPosition> CartPosition { get; set; }
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
User.cs (Model)
namespace BooksDAL.Models
{
public class User
{
[Key]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
[RegularExpression(@"(\+\d{2})*[\d\s-]+", ErrorMessage = "Błędny format numeru telefonu.")]
public string Phone { get; set; }
[EmailAddress(ErrorMessage = "Błędny format adresu e-mail.")]
public string Email { get; set; }
[Timestamp]
public byte[] Timestamp { get; set; }
[NotMapped]
public string FullName => FirstName + " " + LastName;
}
}
IdentityModels.cs
namespace BooksDAL.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Order> Orders { get; set; }
public User UserData { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
AccountController.cs #Register()
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, UserData = new User() };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
AppStart/IdentityConfig.cs
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<BooksEntities>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
Startup.Auth.cs
public partial class Startup
{
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(BooksEntities.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
....
....