move identity in one DbContext (code first) - c#

I have asp.net MVC application, entity framework 6 with code first feature
Here is my code for identity classes
namespace Core.Domain.Identity
{
public partial class AspNetRoles : BaseEntity
{
public AspNetRoles()
{
AspNetUsers = new HashSet<AspNetUsers>();
}
public string RlId { get; set; }
public string Name { get; set; }
public virtual ICollection<AspNetUsers> AspNetUsers { get; set; }
}
public partial class AspNetUserClaims : BaseEntity
{
public string UserId { get; set; }
public string ClaimType { get; set; }
public string ClaimValue { get; set; }
public virtual AspNetUsers AspNetUsers { get; set; }
}
public partial class AspNetUserLogins : BaseEntity
{
//[Key]
//[Column(Order = 0)]
public string LoginProvider { get; set; }
//[Key]
//[Column(Order = 1)]
public string ProviderKey { get; set; }
//[Key]
//[Column(Order = 2)]
public string UserId { get; set; }
public virtual AspNetUsers AspNetUsers { get; set; }
}
public partial class AspNetUsers : BaseEntity
{
public AspNetUsers()
{
AspNetUserClaims = new HashSet<AspNetUserClaims>();
AspNetUserLogins = new HashSet<AspNetUserLogins>();
AspNetRoles = new HashSet<AspNetRoles>();
}
public string UsId { get; set; }
//[StringLength(256)]
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
//[Required]
//[StringLength(256)]
public string UserName { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogins> AspNetUserLogins { get; set; }
public virtual ICollection<AspNetRoles> AspNetRoles { get; set; }
}
}
code for mapping
public partial class AspNetRolesMap : EntityTypeConfiguration<AspNetRoles>
{
public AspNetRolesMap()
{
this.ToTable("AspNetRoles");
this.HasKey(anr => anr.RlId)
.Property(anr => anr.RlId).IsRequired().HasMaxLength(128);
this.Property(anr => anr.Name).IsRequired();
this.HasMany(anr => anr.AspNetUsers)
.WithMany(anr => anr.AspNetRoles)
.Map(m => m.ToTable("AspNetUserRoles").MapLeftKey("RoleId").MapRightKey("UserId"));
}
}
public partial class AspNetUserClaimsMap : EntityTypeConfiguration<AspNetUserClaims>
{
public AspNetUserClaimsMap()
{
this.ToTable("AspNetUserClaims");
this.HasKey(anuc => anuc.Id)
.Property(anuc => anuc.Id).IsRequired();
this.Property(anuc => anuc.ClaimType).IsMaxLength();
this.Property(anuc => anuc.ClaimValue).IsMaxLength();
//this.HasRequired(anuc => anuc.AspNetUsers)
// .WithMany()
// .HasForeignKey(anuc => anuc.UserId);
}
}
public partial class AspNetUserLoginsMap : EntityTypeConfiguration<AspNetUserLogins>
{
public AspNetUserLoginsMap()
{
this.ToTable("AspNetUserLogins");
this.HasKey(x => new { x.LoginProvider, x.ProviderKey, x.UserId });
//this.HasKey(anul => anul.LoginProvider)
//.Property(anul => anul.LoginProvider).HasMaxLength(128).IsRequired();
//this.HasKey(anul => anul.ProviderKey)
// .Property(anul => anul.ProviderKey).HasMaxLength(128).IsRequired();
//this.HasKey(anul => anul.UserId)
// .Property(anul => anul.UserId).HasMaxLength(128).IsRequired();
//this.HasRequired(anul => anul.AspNetUsers)
// .WithMany()
// .HasForeignKey(anul => anul.UserId);
}
}
public partial class AspNetUsersMap : EntityTypeConfiguration<AspNetUsers>
{
public AspNetUsersMap()
{
this.ToTable("AspNetUsers");
this.HasKey(anr => anr.UsId)
.Property(anr => anr.UsId).HasMaxLength(128).IsRequired();
this.Property(anu => anu.EmailConfirmed).IsRequired();
this.Property(anu => anu.PasswordHash).IsMaxLength();
this.Property(anu => anu.SecurityStamp).IsMaxLength();
this.Property(anu => anu.PhoneNumber).IsMaxLength();
this.Property(anu => anu.PhoneNumberConfirmed).IsRequired();
this.Property(anu => anu.TwoFactorEnabled).IsRequired();
this.Property(anu => anu.LockoutEndDateUtc).IsOptional();
this.Property(anu => anu.LockoutEnabled).IsRequired();
this.Property(anu => anu.AccessFailedCount).IsRequired();
this.Property(anu => anu.UserName).HasMaxLength(256).IsRequired();
this.HasMany(anu => anu.AspNetUserClaims)
.WithRequired(anu => anu.AspNetUsers)
.HasForeignKey(anu => anu.UserId);
this.HasMany(anu => anu.AspNetUserLogins)
.WithRequired(anu => anu.AspNetUsers)
.HasForeignKey(anu => anu.UserId);
//this.HasMany(anu => anu.AspNetRoles)
// .WithMany(anu => anu.AspNetUsers)
// .Map(m => m.ToTable("AspNetUserRoles").MapLeftKey("UsId").MapRightKey("Id"));
}
}
and context
public class ApplicationUser : IdentityUser
{
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;
}
}
public class PsCoDbContext : IdentityDbContext<ApplicationUser>, IDbContext
{
public PsCoDbContext() : base("name=DataModel")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach(var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
public static PsCoDbContext Create()
{
return new PsCoDbContext();
}
}
If i start application i get an exception
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The entity types 'IdentityRole' and 'AspNetRoles' cannot share table 'AspNetRoles' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
Can enybody help me what i do wrong?

Related

EF Core Include() gives null after query

I have a project that is running with .net core 6, EF Core 6.0.9, DB -> postgresql 14.
I have these classes
public class Language
{
[Key]
public long Id { get; set; }
public string PublicId { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> CoursesFrom { get; set; }
public virtual ICollection<Course> CoursesTo { get; set; }
}
public class Course
{
[Key]
public long Id { get; set; }
public string PublicId { get; set; }
public string Name { get; set; }
public virtual Language LanguageFrom { get; set; }
public virtual Language LanguageTo { get; set; }
}
The relation is defined as follows:
public class LanguageConfiguration : IEntityTypeConfiguration<Language>
{
public void Configure(EntityTypeBuilder<Language> builder)
{
...
builder.HasMany(l => l.CoursesFrom)
.WithOne(c => c.LanguageFrom);
builder.HasMany(l => l.CoursesTo)
.WithOne(c => c.LanguageTo);
}
}
public class CourseConfiguration : IEntityTypeConfiguration<Course>
{
public void Configure(EntityTypeBuilder<Course> builder)
{
...
builder.HasOne(l => l.LanguageFrom)
.WithMany(c => c.CoursesFrom)
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne(l => l.LanguageTo)
.WithMany(c => c.CoursesTo)
.OnDelete(DeleteBehavior.SetNull);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new LanguageConfiguration());
modelBuilder.ApplyConfiguration(new CourseConfiguration());
}
And LINQ expression
var query = Context.Course
.Include(l => l.LanguageFrom)
.Include(l => l.LanguageTo)
.ToList();
Main entity is returned but fields LanguageFrom and LanguageTo are null - the Include() does nothing. What am I doing wrong?
When there are multiple navigation properties defined between two types shadow navigation properties do not work. You should define two fields to serve as foreign key in the Course entity:
public class Course
{
[Key]
public long Id { get; set; }
public string PublicId { get; set; }
public string Name { get; set; }
public long LanguageFromId { get; set; }
public long LanguageToId { get; set; }
public virtual Language LanguageFrom { get; set; }
public virtual Language LanguageTo { get; set; }
}
Then
public class CourseConfiguration : IEntityTypeConfiguration<Course>
{
public void Configure(EntityTypeBuilder<Course> builder)
{
...
builder.HasOne(l => l.LanguageFrom)
.WithMany(c => c.CoursesFrom)
.HasForeignKey("LanguageFromId")
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne(l => l.LanguageTo)
.WithMany(c => c.CoursesTo)
.HasForeignKey("LanguageToId")
.OnDelete(DeleteBehavior.SetNull);
}
}

Entity Framework Core Navigation Properties Error

I'm trying to make a simple app to try Entity Framework Core, but i a have problem with setting up relations between entities. My entities:
public class Card
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Adress { get; set; }
public DateTime DoB { get; set; }
public DateTime DoS { get; set; }
public User Portal { get; set; }
public List<Reservation> Res { get; set; }
}
public class Doctor
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public TimeSpan Start_Working { get; set; }
public TimeSpan End_Working { get; set; }
public List<Reservation> Reservations { get; set; }
public int SpecID { get; set; }
public Spec Spec { get; set; }
}
public class Reservation
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime DoR { get; set; }
public string Info { get; set; }
public int CardID { get; set; }
public Card Card_Nav_R { get; set; }
public int DoctorID { get; set; }
public Doctor Doctor { get; set; }
}
public class Spec
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public List<Doctor> Doctors { get; set; }
}
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int CardID { get; set; }
public Card Card { get; set; }
}
And a configuration class where i tried to set up relations:
class ApplicationContext:DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Spec> Specs { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder ModelBuilder)
{
ModelBuilder.Entity<User>().HasKey(u => u.Id);
ModelBuilder.Entity<Card>().HasKey(c => c.Id);
ModelBuilder.Entity<Doctor>().HasKey(d => d.Id);
ModelBuilder.Entity<Spec>().HasKey(s => s.Id);
ModelBuilder.Entity<Reservation>().HasKey(r => r.Id);
ModelBuilder.Entity<User>().Property(u => u.Email).IsRequired();
ModelBuilder.Entity<User>().Property(u => u.Password).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Name).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Surname).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.DoB).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Adress).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Name).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Surname).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Email).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Start_Working).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.End_Working).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Info).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Card_Nav_R).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Doctor).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.DoR).IsRequired();
ModelBuilder.Entity<Spec>().Property(s => s.Name).IsRequired();
ModelBuilder.Entity<Doctor>().HasOne<Spec>(d=>d.Spec).WithMany(s => s.Doctors).HasForeignKey(d => d.SpecID);
ModelBuilder.Entity<User>().HasOne<Card>(u => u.Card).WithOne(c => c.Portal).HasForeignKey<User>(u => u.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Card>(r => r.Card_Nav_R).WithMany(c => c.Res).HasForeignKey(r => r.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Doctor>(r => r.Doctor).WithMany(d => d.Reservations).HasForeignKey(r => r.DoctorID);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Simple_Try;Trusted_Connection=True;");
}
}
So, when i tried to add migration or add something to database i saw this error:
System.InvalidOperationException: 'The property or navigation 'Spec' cannot be added to the entity type 'Doctor' because a property or navigation with the same name already exists on entity type 'Doctor'.'
I really don't know how to fix this, i tried to use annotations instead of Fluent API, but had the same result.
The cause of the exception is the following line:
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
because Doctor.Spec is a navigation property
public class Doctor
{
// ...
public Spec Spec { get; set; }
}
and navigation properties cannot be configured via Property fluent API.
So simply remove that line. Whether reference navigation property is required or optional is controlled via relationship configuration. In this case
ModelBuilder.Entity<Doctor>()
.HasOne(d => d.Spec)
.WithMany(s => s.Doctors)
.HasForeignKey(d => d.SpecID)
.IsRequired(); // <--
although the IsRequired is automatically derived from the FK property type - since SpecID is non nullable, then the relationship is required.
For more info, see Required and Optional Properties and Required and Optional Relationships documentation topics.

Entity Framework - The foreign key component … is not a declared property on type

I have the following Model
public class FilanthropyEvent : EntityBase, IDeleteable
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime EventDate { get; set; }
public string Description { get; set; }
public decimal Target { get; set; }
public decimal EntryFee { get; set; }
public bool Deleted { get; set; }
public ICollection<EventAttendee> EventAttendees { get; set; }
}
public class Attendee : EntityBase, IDeleteable
{
public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool MailingList { get; set; }
public bool Deleted { get; set; }
public ICollection<EventAttendee> EventAttendees { get; set; }
}
Events and Attendees is a many to many relationship but I needed another property on the association so I created an association entity
public class EventAttendee : EntityBase
{
public int FilanthropyEventId { get; set; }
public int AttendeeId { get; set; }
public bool InActive { get; set; }
public virtual Attendee Attendee { get; set; }
public virtual FilanthropyEvent FilanthropyEvent { get; set; }
}
These are the configurations for each FilanthropyEvent and Attendee
public class FilanthropyEventConfiguration : EntityTypeConfiguration<FilanthropyEvent>
{
public FilanthropyEventConfiguration()
{
HasKey(x => x.Id);
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(x => x.EventAttendees).WithRequired(x => x.FilanthropyEvent).HasForeignKey(x => x.FilanthropyEvent);
}
}
public AttendeeConfiguration()
{
HasKey(x => x.Id);
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(x => x.EventAttendees).WithRequired(x => x.Attendee).HasForeignKey(x => x.AttendeeId);
}
public class EventAttendeesConfiguration : EntityTypeConfiguration<EventAttendee>
{
public EventAttendeesConfiguration()
{
HasKey(x => new {x.FilanthropyEventId, x.AttendeeId});
}
}
When I try and initialise the database via the update-database command in the package manager console I get the following error.
System.InvalidOperationException: The foreign key component 'FilanthropyEvent' is not a declared property on type 'EventAttendee'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
I realise I'm probably missing a mapping in the EventAttendeesConfiguration class but what would be the correct mapping to model this relationship?
This code
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEvent);
Should be
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEventId);

Mapping not working?

I have a weird situtation, i have 1 master class called User, this is an abstract class. It cointains 3 child classes (Student, Promotor and BPC) who always inherit from User.
I am using the TPH (Table per Hierarchy) structure to map this to the database, the Discriminator field is just the name of the class.
a Student has a relationship with Promotor. It can contain 0 or 1 promotor. With the initializer i make sure that a Student has the corresponding promotor. (it shows correctly in my database after launch)
When i try to use the modelbinder to get the Student from the logged in user it returns the correct student but it says it doesnt contain a promotor.
Class User:
public abstract class User
{
//TPH is default
public int Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Username { get; set; }
public String Email { get; set; }
public String Salt { get; set;}
public String Password { get; set; }
public DateTime LastLogin { get; set; }
public String LastIp { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime CreationDate { get; set; }
[NotMapped]
public String PlainPassword { get; set; }
}
Class Student
public class Student : User
{
public virtual Promotor Promotor { get; set; }
public virtual CoPromotor CoPromotor { get; set; }
public virtual ICollection<Suggestion> Suggestions { get; set; }
public Student()
{
Suggestions = new Collection<Suggestion>();
}
}
Class Promotor
public class Promotor : User
{
public virtual ICollection<Student> Students { get; set; }
public List<User> users;
private String message;
public Promotor()
{
Students = new Collection<Student>();
users = new List<User>();
}
}
User model binder
public class UserModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext.HttpContext.User.Identity.IsAuthenticated)
{
IUserRepository repos =
(IUserRepository) DependencyResolver.Current.GetService(typeof (IUserRepository));
return repos.FindByUsername(controllerContext.HttpContext.User.Identity.Name);
}
return null;
}
}
Action in the controller
[HttpPost]
public ActionResult Create(CreateViewModel model, User user, string btnSaveSend)
{
var student = (Student) user; //here the attribute Promotor is NULL
}
User mapper:
public class UserMapper : EntityTypeConfiguration<User>
{
public UserMapper()
{
ToTable("user");
// Primary key
HasKey(u => u.Id);
// Properties
Property(u => u.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(u => u.FirstName).IsRequired();
Property(u => u.LastName).IsRequired();
Property(u => u.Email).IsRequired();
Property(u => u.Salt).IsRequired();
Property(u => u.Username).IsRequired();
Property(u => u.Password).IsRequired();
Property(u => u.LastLogin);
Property(u => u.LastIp);
Property(u => u.CreationDate).IsRequired();
Property(u => u.LastPasswordChangedDate).IsRequired();
}
}
Student Mapper
public class StudentMapper : EntityTypeConfiguration<Student>
{
public StudentMapper()
{
HasMany(s => s.Suggestions).WithRequired(s => s.Student);
HasRequired(s => s.Promotor).WithMany(s => s.Students);
}
}
UserRepository:
public User FindByUsername(string name)
{
return users.FirstOrDefault(u => u.Username.ToLower() == name.ToLower());
}

SimpleMembership with custom table using EF Code First

I was following HTML5 Line of business course on pluralsight to use Simple membership. I use the same code but getting error while Creating account using SimpleMembership with custom table. I cant find whats wrong in it. Can anybody help?
Invalid column name 'ConfirmationToken'. Invalid column name
'PasswordChangedDate'. Invalid column name
'PasswordFailuresSinceLastSuccess'.
Here is my code
Register Method:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
new
{
FirstName = "Admin",
LastName = "Admin",
IsActive = true,
CreatedOn = DateTime.Now,
ModifiedOn = DateTime.Now
});
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
Entities:
public class Membership
{
public int UserId {get; set;}
public DateTime? CreateDate { get; set; }
public string ConfirmationTokeen { get; set; }
public bool? IsConfirmed { get; set; }
public DateTime? LastPaswordFailureDate { get; set; }
public int PasswordFailureSinceLastSuccess { get; set; }
public string Password { get; set; }
public DateTime? PasswordChangeDate { get; set; }
public string PasswordSalt { get; set; }
public string PasswordVerificationToken { get; set; }
public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
}
public class OAuthMembership
{
public string Provider { get; set; }
public string ProviderUserId { get; set; }
public int UserId { get; set; }
}
public class Role
{
public int RoleId {get; set;}
public string RoleName {get; set;}
public ICollection<User> Users { get; set; }
public Role()
{
this.Users = new List<User>();
}
}
public class User : IAuditInfo
{
public int Id {get; set;}
public string Username{get; set;}
public string FirstName {get; set;}
public string LastName { get; set; }
public bool IsActive{get; set;}
public DateTime? CreatedOn { get; set; }
public DateTime? ModifiedOn {get; set;}
public ICollection<Role> Roles { get; set; }
public User()
{
this.Roles = new List<Role>();
}
}
Configuration
public UserConfiguration()
{
this.Property(p => p.Id).HasColumnOrder(0);
this.Property(p => p.Username).IsRequired().HasMaxLength(200);
this.Property(p => p.FirstName).IsOptional().HasMaxLength(100);
this.Property(p => p.LastName).IsOptional().HasMaxLength(100);
this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("webpages_UsersInRoles");
});
}
public RoleConfiguration()
{
this.ToTable("webpages_Roles");
this.Property(p => p.RoleName).HasMaxLength(256).HasColumnType("nvarchar").IsRequired();
}
public OAuthMembershipConfiguration()
{
this.ToTable("webpages_OAuthMembership");
this.HasKey(k => new { k.Provider, k.ProviderUserId });
this.Property(p => p.Provider).HasMaxLength(128).HasColumnType("nvarchar").IsRequired();
this.Property(p => p.ProviderUserId).HasMaxLength(128).HasColumnType("nvarchar").IsRequired();
this.Property(p => p.UserId).IsRequired();
}
public MembershipConfiguration()
{
this.ToTable("webpages_Membership");
this.HasKey(s => s.UserId);
this.Property(p => p.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(p => p.ConfirmationTokeen).HasMaxLength(128).HasColumnType("nvarchar");
this.Property(p => p.PasswordFailureSinceLastSuccess).IsRequired();
this.Property(p => p.Password).IsRequired().HasMaxLength(128).HasColumnType("nvarchar");
this.Property(p => p.PasswordSalt).IsRequired().HasMaxLength(128).HasColumnType("nvarchar");
this.Property(p => p.PasswordVerificationToken).HasMaxLength(128).HasColumnType("nvarchar");
}
Filter:
public SimpleMembershipInitializer()
{
DataContext context = new DataContext();
context.Database.Initialize(true);
try
{
if (!context.Database.Exists())
{
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
WebSecurity.InitializeDatabaseConnection(
Config.ConnectionStringName,
Config.UsersTableName,
Config.UsersPrimaryKeyColumnName,
Config.UsersUsernameColumnName,
autoCreateTables: true);
}
catch (Exception ex)
{
}
}

Categories