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)
{
}
}
Related
A user can add an event they want to their favorites. Below are the entities I have opened for this and the links between them.
Event:
public class Event : EntitySoftDeletableIntKey
{
public string Title { get; set; }
public string ShortContent { get; set; }
public string Place { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int EventDetailId { get; set; }
public EventDetail EventDetail { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public List<Tag>? Tags { get; set; } = new List<Tag>();
public List<Comment>? Comments { get; set; } = new List<Comment>();
public ApplicationUser? ApplicationUser { get; set; }
public int? ApplicationUserId { get; set; }
public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
public List<FavoriteEvent>? FavoriteEvents { get; set; }
}
User:
public class ApplicationUser : IdentityUser<int>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<FavoriteEvent>? FavoriteEvents { get; set; } = new List<FavoriteEvent>();
public List<Event>? Events { get; set; } = new List<Event>();
public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
}
FavoriteEvent :
public class FavoriteEvent : EntitySoftDeletableIntKey
{
public int? EventId;
public Event? Event;
public int? ApplicationUserId { get; set; }
public ApplicationUser? ApplicationUser { get; set; }
}
Link Bbetween :
modelBuilder.Entity<FavoriteEvent>()
.HasKey(fe => new { fe.EventId, fe.ApplicationUserId });
modelBuilder.Entity<FavoriteEvent>()
.HasOne(fe => fe.Event)
.WithMany(e => e.FavoriteEvents)
.HasForeignKey(ae => ae.EventId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<FavoriteEvent>()
.HasOne(fe => fe.ApplicationUser)
.WithMany(u => u.FavoriteEvents)
.HasForeignKey(fe => fe.ApplicationUserId).OnDelete(DeleteBehavior.Restrict);
When the user adds an event to the favoriteevent list, I get the error in the header. I couldn't solve it anyway. Thank you in advance for your help.
public async Task<Unit> Handle(AddEventToFavCommandRequest request, CancellationToken cancellationToken)
{
var #event = await _unitOfWork.GetReadRepository<Event>().GetSingle(e => e.Id == request.EventId);
var currentUser = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == request.ApplicationUserId);
currentUser.FavoriteEvents.Add(new FavoriteEvent()
{
EventId = #event.Id,
ApplicationUserId = currentUser.Id
});
return Unit.Value;
}
public async Task<int> Save(CancellationToken cancellationToken = new CancellationToken())
{
var datas = _context.ChangeTracker.Entries<EntitySoftDeletableIntKey>();
foreach (var data in datas)
{
_ = data.State switch
{
EntityState.Added => data.Entity.CreatedDate = DateTime.UtcNow,
EntityState.Modified => data.Entity.ModifiedDate = DateTime.UtcNow,
};
}
return await _context.SaveChangesAsync(cancellationToken);
}
I'm trying to learn .Net Core 2.1 and testing a little project with already existing database. We have 3 tables (Template, TemplateDesc, TemplateParameter) with one of them has one-to-many relationship. When I get one Template with controller, it returns null for TemplateDescriptions and ParameterValues. Also if I try to delete Template, it returns FK exception. Can someone point the problem with the below codes?
Note : I use Swagger extension to test codes.
public class Template
{
public decimal CompanyCode { get; set; }
public string TemplateCode { get; set; }
public List<TemplateDesc> TemplateDescriptions { get; set; }
public DateTime TemplateDate { get; set; }
public string RuleCode { get; set; }
public string SourceTypeCode { get; set; }
public string Description { get; set; }
public bool IsBlocked { get; set; }
public string CreatedUserName { get; set; }
public DateTime CreatedDate { get; set; }
public List<TemplateParameter> ParameterValues { get; set; }
}
public class TemplateDesc
{
public decimal CompanyCode { get; set; }
public string TemplateCode { get; set; }
public string LangCode { get; set; }
public string TemplateDescription { get; set; }
}
public class TemplateParameter
{
public decimal CompanyCode { get; set; }
public string TemplateCode { get; set; }
public string TemplateRuleCode { get; set; }
public string ParameterName { get; set; }
public string ParameterValue { get; set; }
}
modelBuilder.Entity<Template>(entity =>
{
entity.HasKey(e => new { e.CompanyCode, e.TemplateCode });
entity.HasMany(e => e.TemplateDescriptions).WithOne(e => e.Template).HasForeignKey(e => new { e.CompanyCode, e.TemplateCode });
entity.HasMany(e => e.ParameterValues).WithOne(e => e.Template).HasForeignKey(e => new { e.CompanyCode, e.TemplateCode });
}
modelBuilder.Entity<TemplateDesc>(entity =>
{
entity.HasKey(e => new { e.CompanyCode, e.TemplateCode, e.LangCode });
entity.HasOne(e => e.Template).WithMany(e => e.TemplateDescriptions).HasForeignKey(e => new { e.CompanyCode, e.TemplateCode }).OnDelete(DeleteBehavior.Cascade);
}
modelBuilder.Entity<TemplateParameter>(entity =>
{
entity.HasKey(e => new { e.CompanyCode, e.TemplateCode, e.TemplateRuleCode, e.ParameterName});
entity.HasOne(e => e.Template).WithMany(e => e.ParameterValues).HasForeignKey(e => new { e.CompanyCode, e.TemplateCode}).OnDelete(DeleteBehavior.Cascade);
}
[HttpGet]
public ActionResult<Template> GetWithKey([FromQuery] decimal companyCode, [FromQuery] string templateCode)
{
try
{
var template = this.mRepository.Find(e => e.CompanyCode == companyCode && e.TemplateCode.AreEqual(templateCode)).FirstOrDefault();
if (template == null)
return new JsonResult(new ApiResponse<Template>(ResponseType.Exception, null));
return new JsonResult(new ApiResponse<Template>(ResponseType.Success, template));
}
catch
{
throw;
}
}
[HttpDelete]
public ActionResult DeleteWithKey([FromQuery] decimal companyCode, [FromQuery] string templateCode)
{
if (this.mRepository.Find(e => e.CompanyCode == companyCode && e.TemplateCode.AreEqual(templateCode)).Count() < 1)
return new JsonResult(new ApiResponse<string>(ResponseType.NotFound, templateCode));
this.mRepository.Delete(companyCode, templateCode);
return new JsonResult(new ApiResponse<Template>(ResponseType.Success, null));
}
You have to either use lazy loading, or use Include construct:
db.Templates
.Include(x => x.TemplateDesc)
.Include(x => x.TemplateParameter)
.FirstOrDefault(...)
the includes can be put in extension method:
public IQueryable<Template> BuildTemplate(this DbSet<Template> set)
{
return set.Include(x => x.TemplateDesc)
.Include(x => x.TemplateParameter);
}
Then you can use
dbContext.Templates.BuildTemplate.FirstOrdefault(x => x.TemplateDescriptions.Any(td => td.TemplateCode == "xyz"));
It is my first a many-to-many relation consisting of Team, User and TeamUser objects. In TeamController I mapped TeamForCreationDto to Team, but ICollection Members was empty. Some bug in CreateMap?Q1: How it should be combined to fill all property and tables by EF? Now I have "for" loop and there created/added TeamUser.
Q2: If I must fill both property AdminId and Admin?
A2: No, after adding Admin, property AdminId in DB thanks EF will find value automatically.
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int AdminId { get; set; }
public User Admin { get; set; }
//public int[] MembersId { get; set; }
public ICollection<TeamUser> Members { get; set; }
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Team> TeamsAsAdmin { get; set; }
public ICollection<TeamUser> TeamsAsMember { get; set; }
}
public class TeamUser
{
public int TeamId { get; set; }
public Team Team { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Relations between tables in ModelBuilder
builder.Entity<Team>()
.HasOne(t => t.Admin)
.WithMany(u => u.TeamsAsAdmin)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<TeamUser>()
.HasKey(tu => new { tu.TeamId, tu.UserId });
builder.Entity<TeamUser>()
.HasOne(tu => tu.User)
.WithMany(u => u.TeamsAsMember)
.HasForeignKey(tu => tu.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<TeamUser>()
.HasOne(tu => tu.Team)
.WithMany(t => t.Members)
.HasForeignKey(tu => tu.TeamId);
My CreateMap in AutoMapperProfiles()
CreateMap<TeamForCreationDto, Team>().ReverseMap().ForMember(u => u.MembersId, opt => opt.MapFrom(x => x.Members));
My TeamController.cs
public async Task<IActionResult> Create(int userId, TeamForCreationDto teamForCreationDto)
{
if (await _repoTeams.TeamExists(teamForCreationDto.Name))
return BadRequest("A team with this name already exists!");
var mappedTeam = _mapper.Map<Team>(teamForCreationDto);
//mappedTeam.AdminId = userId;
mappedTeam.Admin = await _repoUsers.GetUser(userId);
_repoTeams.Add(mappedTeam);
for (int i = 0; i < teamForCreationDto.MembersId.Length; i++)
{
TeamUser tm = new TeamUser();
tm.Team = mappedTeam;
tm.User = await _repoUsers.GetUser(teamForCreationDto.MembersId[i]);
_repoTeams.Add(tm);
}
await _repoTeams.SaveAll();
}
TeamForCreationDto.cs
public class TeamForCreationDto
{
int Id { get; set; }
public string Name { get; set; }
public string PhotoUrl { get; set; }
public int[] MembersId { get; set; }
}
I try to migrate a small application to Entity Framework Core but I cant get the many to many relation to work.
First my Entities
public class Currency : Entity<int>, IMayHaveUser
{
public string Code { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public virtual List<CountryCurrency> CountryCurrencies { get; set; }
public bool IsUserDefined => User != null;
[ForeignKey("UserId")]
public virtual User User { get; set; }
public long? UserId { get; set; }
}
public class Country : Entity<int>, IMayHaveUser
{
public string Iso2Code { get; set; }
public virtual ICollection<Era> Eras { get; set; }
public string Name { get; set; }
public virtual List<CountryCurrency> CountryCurrencies { get; set; }
[NotMapped]
public bool IsUserDefined => User != null;
[ForeignKey("UserId")]
public virtual User User { get; set; }
public long? UserId { get; set; }
}
public class CountryCurrency : Entity<Guid>
{
public int CountryId { get; set; }
public Country Country { get; set; }
public int CurrencyId { get; set; }
public Currency Currency { get; set; }
}
and my DbContext is
modelBuilder.Entity().HasKey(currency => new {
currency.CountryId, currency.CurrencyId });
modelBuilder.Entity()
.HasOne(pt => pt.Country)
.WithMany(p => p.CountryCurrencies)
.HasForeignKey(pt => pt.CountryId);
modelBuilder.Entity<CountryCurrency>()
.HasOne(pt => pt.Currency)
.WithMany(t => t.CountryCurrencies)
.HasForeignKey(pt => pt.CurrencyId);
now when I add a currency for example
Currency currency;
Country country;
CountryCurrency countryCurrency;
currency = new Currency();
currency.Id = i++;
currency.User = null;
currency.Code = "ETB";
currency.Name = "Ethiopian Birr";
currency.Symbol = "Br";
country =
this._context.Countries.FirstOrDefault(
country1 => country1.Iso2Code == "ET");
if (country != null)
{
currency.CountryCurrencies = new List<CountryCurrency>();
countryCurrency = new CountryCurrency();
countryCurrency.Country = country;
countryCurrency.Currency = currency;
currency.CountryCurrencies.Add(countryCurrency);
this.InitialCurrencies.Add(currency);
}
this._context.Currencies.Add(currency);
so when now I'm retrieve the data in my test I get this with this code
Country = context.Countries.Include(country => country.CountryCurrencies).First();
I can't get the currency the id is set but the property not...
You have also to include the currency entity, not just the join entity
Country = context.Countries
.Include(country => country.CountryCurrencies)
.ThenInclude(e => e.Currency)
.First();
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?