Error with mapping entities in EF - c#

I am trying to implement Asp.net Identity 2.0 with DB first.
I have imported my model.edmx into the project. It contains all the tables I need with the correct information and structure.
In the database there is a table called 'FSKUsers' I have edited this to contain the needed fields of the AspNetUsers which is the default table for Identity 2.0
So in my Identity DB Context I have mapped my FskUser class (which is a high level user for Identity sake)
public class IdentityDbContext : IdentityDbContext<FskUser, FskRole, int, FskUserLogin, FskUserRole, FskUserClaim>
{
public IdentityDbContext()
: base("FSK_FskNetworksEntities")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var userEntity = modelBuilder.Entity<FskUser>();
userEntity.ToTable("FSKUsers", "dbo");
userEntity.Property(p => p.Id).HasColumnName("FSKUserId");
userEntity.Property(p => p.PasswordHash).HasColumnName("Password");
}
public static IdentityDbContext Create()
{
return new IdentityDbContext();
}
}
So basically I want to map the class FskUser to the Data Base table called FSKUser which is also contained in my .edmx model.
When I run the website I get the following error.
The entity type FskUser is not part of the model for the current context
My two POCO classes:
The one from my edmx model:
public partial class FSKUser
{
public FSKUser()
{
this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
this.FSKDevices = new HashSet<FSKDevice>();
this.FSKEventLogs = new HashSet<FSKEventLog>();
this.FSKReports = new HashSet<FSKReport>();
this.FSKTransactions = new HashSet<FSKTransaction>();
this.FSKTriggers = new HashSet<FSKTrigger>();
this.UdlDownloads = new HashSet<UdlDownload>();
this.AspNetRoles = new HashSet<AspNetRole>();
this.FSKCompanies = new HashSet<FSKCompany>();
}
public int FSKUserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public string Password { get; set; }
public string SecurityStamp { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public byte FSKAccessLevelId { get; set; }
public string AddressStreet1 { get; set; }
public string AddressStreet2 { get; set; }
public string AddressStreet3 { get; set; }
public string AddressPostCode { get; set; }
public Nullable<int> CreatorId { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string ConfirmationToken { get; set; }
public Nullable<bool> IsConfirmed { get; set; }
public Nullable<System.DateTime> LastPasswordFailureDate { get; set; }
public Nullable<int> PasswordFailuresSinceLastSuccess { get; set; }
public Nullable<System.DateTime> PasswordChangedDate { get; set; }
public string PasswordVerificationToken { get; set; }
public string PasswordVerificationTokenExpirationDate { get; set; }
public bool IsDeleted { get; set; }
public Nullable<int> CostCentreId { get; set; }
public Nullable<int> AdminPasswordResetUserId { get; set; }
public Nullable<System.DateTime> PreviousLogInDate { get; set; }
public System.Guid msrepl_tran_version { get; set; }
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual ICollection<FSKDevice> FSKDevices { get; set; }
public virtual ICollection<FSKEventLog> FSKEventLogs { get; set; }
public virtual ICollection<FSKReport> FSKReports { get; set; }
public virtual ICollection<FSKTransaction> FSKTransactions { get; set; }
public virtual ICollection<FSKTrigger> FSKTriggers { get; set; }
public virtual ICollection<UdlDownload> UdlDownloads { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
public virtual ICollection<FSKCompany> FSKCompanies { get; set; }
}
The one I use in my Identity Config
public class FskUser : IdentityUser<int, FskUserLogin, FskUserRole, FskUserClaim>
{
[Display(Name = "First Name")]
[Required(ErrorMessage = "First Name is Required.")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last Name is Required.")]
public string LastName { get; set; }
[MaxLength(20)]
[Display(Name = "Cell Number")]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
[StringLength(10, ErrorMessage = "The {0} must be 10 numbers long.", MinimumLength = 10)]
public override string PhoneNumber { get; set; }
[Display(Name = "Access Level")]
public byte? FSKAccessLevelId { get; set; }
[Display(Name = "Street Address 1")]
public string AddressStreet1 { get; set; }
[Display(Name = "Street Address 2")]
public string AddressStreet2 { get; set; }
[Display(Name = "Street Address 3")]
public string AddressStreet3 { get; set; }
[Display(Name = "Postal Code")]
public string AddressPostCode { get; set; }
[Display(Name = "Previous Login")]
public Nullable<DateTime> PreviousLogInDate { get; set; }
[Display(Name = "Account Confirmed")]
public Nullable<bool> IsConfirmed { get; set; }
[Display(Name = "Last Password Failier")]
public Nullable<DateTime> LastPasswordFailureDate { get; set; }
[Display(Name = "Password Last Changed")]
public Nullable<DateTime> PasswordChangedDate { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<FskUser, int> manager)
{
//TODO: add option for web and api (to create different auth types
// 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;
}
}

When you use Database first approach with edmx file OnModelCreating method is never called. You may check that with debugger.

Related

I want to add AspNetUsers table "Id" column as Foreign Key in another table

ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Hospital> Hospitals { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
}
}
Hospital.cs
public class Hospital : Common
{
[Key]
[Column(Order = 1)]
public int HospitalId { get; set; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Invalid e-mail address.")]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Contact Person")]
public string ContactPerson { get; set; }
[Required]
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
public string PhoneNum { get; set; }
[Required]
[MinLength(10)]
[Display(Name = "Mobile Number")]
public string MobileNum { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[Display(Name = "Short Name")]
public string ShortName { get; set; } //Unique Slug name
}
Common.cs
public class Common
{
public DateTime? CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime? EditedOn { get; set; }
public string EditedBy { get; set; }
public DateTime? DeletedOn { get; set; }
public string DeletedBy { get; set; }
public bool? IsDeleted { get; set; } = false;
public bool? IsActive { get; set; } = true;
}
I want to add the primary key of the AspNetUsers table in the Hospital table as foreign key with these columns:
CreatedBy
EditedBy
DeletedBy
Main Goal: So using this kind of relationship I want to display the User Name with Hospital details, who is Create/Edit/Delete hospital details.
I don't recommend between two table more than one relation. I think, There's no need forgein relations for these colums. Bcs these colums're just information coll. But still you can edit common class like this.
public class Common
{
public DateTime? CreatedOn { get; set; }
[ForeignKey("AspNetUsers")] public string CreatedBy { get; set; }
public AspNetUsers CreatedByUser { get; set; }
public DateTime? EditedOn { get; set; }
[ForeignKey("AspNetUsers")] public string EditedBy { get; set; }
public AspNetUsers EditedByUser { get; set; }
public DateTime? DeletedOn { get; set; }
[ForeignKey("AspNetUsers")] public string DeletedBy { get; set; }
public AspNetUsers DeletedByUser { get; set; }
public bool? IsDeleted { get; set; } = false;
public bool? IsActive { get; set; } = true;
}
Configure the relasionship using the data annotation:
in Hospital class add the following attribute :
public int AspNetUsersId{ get; set; }
[ForeignKey("AspNetUsersId")]
public virtual Common aspNetUser { get; set; }
and in Common class add the Hospital Attribute:
public virtual Hospital hospital { get; set; }
Now, you should define this relation in ApplicationDvContext :
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Hospital>()
.HasOptional(s => s.aspNetUser)
.WithRequiredPrincipal(ad => ad.hospital);
}
You should configure your database from a management program with the key-relationships you want and then update the entity data model from your solution, otherwise Entity won't be able to find the relationship by itself. If you are using microsoft sql management studio check this article.

How to replicate autogenerated primary key into another table

In ASP.NET Core MVC, I am using code first migration. I have these two models:
Models:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class Student
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(20)]
public string FirstName { get; set; }
[Required]
[StringLength(20)]
public string LastName { get; set; }
[Required]
[StringLength(40)]
public string Guardian { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
public bool AdminPermition { get; set; }
}
Then the two are in a single ViewModel:
ViewModel:
public class StudentRegisterModel
{
[Required]
[StringLength(20)]
public string FirstName { get; set; }
[Required]
[StringLength(20)]
public string LastName { get; set; }
[Required]
[StringLength(40)]
public string Guardian { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string ConfirmPassword { get; set; }
}
Everything is saved using this service:
Service:
public async Task<bool> RegistrationService(StudentRegisterModel registerModel)
{
try
{
//validation functions
var context = new ValidationContext(registerModel, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(registerModel, context, results, true))
{
if (CheckEmailAvailability(registerModel.Email)){
if (registerModel.Password != registerModel.ConfirmPassword)
return false;
Student student = new Student
{
FirstName = registerModel.FirstName,
LastName = registerModel.LastName,
Email = registerModel.Email,
Guardian = registerModel.Guardian,
DateOfBirth = registerModel.DateOfBirth,
AdminPermition = false
};
User user = new User
{
Email = registerModel.Email,
Password = Encoder(registerModel.Password),
};
_context.Add(student);
_context.Add(user);
await _context.SaveChangesAsync();
return true;
}
}
return false;
}
catch
{
return false;
}
}
The Id in User is auto-generated, while the Id in Student is not.
How do I automatically duplicate the Id in User into the Id in Student?
Thanks
I think something like this should work:
public class User
{
[Key]
public int Id { get; set; }
[InverseProperty("Student")]
public Student Student { get; set; }
// ...
}
public class Student
{
[Key]
public int Id { get; set; }
[ForeignKey("Id")]
public User User { get; set; }
// ...
}

How to use Automapper with Object in Object

I want to Map two types of Objects but I didn't find the way to do it.
User class:
public partial class TUser
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("login")]
[StringLength(50)]
public string Login { get; set; }
[Column("password")]
[StringLength(50)]
public string Password { get; set; }
[Column("role")]
[StringLength(50)]
public string Role { get; set; }
[Column("isDeleted")]
public bool? IsDeleted { get; set; }
[Column("avatarUrl")]
[StringLength(50)]
public string AvatarUrl { get; set; }
[Column("iso")]
[StringLength(2)]
public string Iso { get; set; }
[Column("lastLogonDate", TypeName = "datetime")]
public DateTime? LastLogonDate { get; set; }
[Column("createdDate", TypeName = "datetime")]
public DateTime? CreatedDate { get; set; }
[Column("lastUpdatedDate", TypeName = "datetime")]
public DateTime? LastUpdatedDate { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
[InverseProperty("IdNavigation")]
public virtual TWorker TWorker { get; set; }
}
UserForLogin Class:
public class UserForLogin
{
public int Id { get; set; }
public string Login { get; set; }
public string Role { get; set; }
public string AvatarUrl { get; set; }
public string Iso { get; set; }
public TWorker TWorker { get; set; }
}
TWorker class:
public partial class TWorker
{
public TWorker()
{
TWorkerToWorkType = new HashSet<TWorkerToWorkType>();
TrEventToWorker = new HashSet<TrEventToWorker>();
TrWorkerToWorkerCategory = new HashSet<TrWorkerToWorkerCategory>();
}
[Key]
[Column("id")]
public int Id { get; set; }
[Column("lastname")]
[StringLength(50)]
public string Lastname { get; set; }
[Column("firstname")]
[StringLength(50)]
public string Firstname { get; set; }
[Column("email")]
[StringLength(50)]
public string Email { get; set; }
[Column("phone")]
[StringLength(50)]
public string Phone { get; set; }
[Column("address")]
[StringLength(50)]
public string Address { get; set; }
[Column("postcode")]
[StringLength(50)]
public string Postcode { get; set; }
[Column("locality")]
[StringLength(50)]
public string Locality { get; set; }
[Column("workerCategoryKey")]
public int? WorkerCategoryKey { get; set; }
[Column("sexe")]
[StringLength(50)]
public string Sexe { get; set; }
[ForeignKey(nameof(Id))]
[InverseProperty(nameof(TUser.TWorker))]
public virtual TUser IdNavigation { get; set; }
[InverseProperty("WorkerKeyNavigation")]
public virtual ICollection<TWorkerToWorkType> TWorkerToWorkType { get; set; }
[InverseProperty("WorkerKeyNavigation")]
public virtual ICollection<TrEventToWorker> TrEventToWorker { get; set; }
[InverseProperty("WorkerKeyNavigation")]
public virtual ICollection<TrWorkerToWorkerCategory> TrWorkerToWorkerCategory { get; set; }
}
AutoMapperProfiles class:
public AutoMapperProfiles()
{
CreateMap<TUser, UserForLogin>()
.ForMember(
dest => dest.TWorker,
opt => opt.MapFrom(src => src.TWorker)
);
}
But TWorker is always null and I can't find what am I doing wrong?
If I use TUser only to return my object without Automapper code, TWorker contains the values I want.
You just need to implement the map for the subObject and autoMapper will handle it for you.
To be precise, if you map a property to another property which has a different type, autoMapper will try to find a corresponding map.

Webpage not available MVC 4

My application was working fine until I added 3 new classes(Administrator,Department and Depot) and altered the IssueContext.cs in the Data Access Layer.
Since my IssueContext has been altered I needed to update my database so I used update-database in the Package Manager Console then I got this(Open tab in the new window)
Which is weird because it was working perfectly fine before. I then installed Entity Framework then update-database worked.
However when I click on my User tabs or About tabs they give me a "Webpage not available" but the Index page works. Could this be a relational database mapping problem where I didn't map my new classes correctly?
Note: I also tried installing MVC but MVC Razor just crashes everything.
Here's my Entity Diagram
User.cs
public class User
{
public int UserID { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public string FullName
{
get { return LastName + ", " + FirstMidName; }
}
public int AdministratorID { get; set; }
[ForeignKey("AdministratorID")]
public virtual Administrator Administrator { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public int TicketID { get; set; }
//Setting up relationships A use can apply for any number of tickets, so Tickets is defined as a collection of Ticket entities.
public virtual ICollection<Ticket> Users { get; set; }
}
Ticket.cs
public class Ticket
{
public string Issue { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
//Category One to Many Ticket
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
//User (One to Many) Ticket
public int UserID { get; set; }
public int TicketID { get; set; }
[ForeignKey("TicketID")]
public virtual User User { get; set; }
public int AdminID { get; set; }
public virtual ICollection<Administrator> Administrators { get; set; }
}
Depot.cs
public class Depot
{
public int DepotID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Department.cs
public class Department
{
public int DepartmentID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Category.cs
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string Title { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
Administrator.cs
public class Administrator
{
[Key, ForeignKey("User")]
public int UserID { get; set; }
public int AdminID { get; set; }
public int TicketID { get; set; }
[StringLength(50)]
public string AdminRole { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
public virtual User User { get; set; }
}
Context.cs
public class IssueContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Administrator> Administrators { get; set; }
public DbSet<Depot> Depots { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Ticket>()
.HasMany(c => c.Administrators).WithMany(i => i.Tickets)
.Map(t => t.MapLeftKey("TicketID")
.MapRightKey("AdministratorID")
.ToTable("AdministratorsTickets"));
modelBuilder.Entity<Administrator>()
.HasKey(e => e.UserID);
modelBuilder.Entity<User>()
.HasOptional(s => s.Administrator) // Mark StudentAddress is optional for Student
.WithRequired(ad => ad.User); // Create inverse relationship
}
}

how to determine that my model pass all data annotations rule check or not?

I have scenario where I want to know is my model is valid or not.
here is my model
public class CallPartyModel
{
public System.Guid PartyId { get; set; }
public System.Guid FwCallMasterId { get; set; }
[Required(ErrorMessage = "Principal Party is required.")]
[Display(Name = "Principal Party")]
public System.Guid PrincipalPartyId { get; set; }
[Required(ErrorMessage = "Responsible Party is required.")]
[Display(Name = "Responsible Party")]
public System.Guid ResponsiblePartyId { get; set; }
[Display(Name = "File Type")]
public System.Guid FileTypeId { get; set; }
[Display(Name = "Agent Type")]
public Nullable<System.Guid> AgentTypeId { get; set; }
public string AgentTypeCode { get; set; }
public bool AdvancedRequired { get; set; }
public bool SeperateDARequired { get; set; }
public string PrincipalPartyName { get; set; }
public string ResponsiblePartyName { get; set; }
public string PrincipalReferenceCode { get; set; }
public string ResponsibleReferenceCode { get; set; }
public string FileTypeName { get; set; }
public string FileTypeCode { get; set; }
public string AgentTypeName { get; set; }
public bool? DAIssuedFlag { get; set; }
[Range(0, 999999999.999, ErrorMessage = "Value lies outside the 0 to 999999999.999 range")]
public decimal? AdvanceReceivedAmount { get; set; }
public System.Guid CreatedBy { get; set; }
public System.DateTime CreatedDateTime { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDateTime { get; set; }
public bool IsDeleted { get; set; }
public Nullable<System.Guid> DeletedBy { get; set; }
public Nullable<System.DateTime> DeletedDateTime { get; set; }
//public virtual UserModel FwCore_Users { get; set; } //Created By User
//public virtual UserModel FwCore_Users1 { get; set; }//Modified By User
//public virtual UserModel FwCore_Users2 { get; set; }// Deleted by User
public bool IsDirtyCheck { get; set; }
public bool LockPrinFlag { get; set; }
public string LockPrinMsg { get; set; }
}
I have defined some rules for this ex. public decimal? AdvanceReceivedAmount { get; set; }
the range rule.
I know how to check model state when our model is bonded to view as ModelState.Isvalid()
but in my code I am working with tow diffident models, its in some wcf service, where I am getting the input as string for all properties and I can't define the data annotation rule on second model. So I have to transfer the data manually from model one to model two and in model two (CallPartyModel) I have define the data annotation rules. Now before performing any transaction in database, I have to check if the model properties's value are valid or not, I know I can do it manually but is there any method as modelState.IsValid() for this kind of scenario?
as:
CallPartyModel obj=new CallPartyModel();
obj.AdvanceReceivedAmount=88.88;
if(obj.IsValid())
{
//go
}
else
{
//Show the error according to property
}
Any suggestion or help will be appreciated
How about you check your model1 against model2 by loading the model2 with the values of Model1 and then using
Model2 m2 = new Model2();
//... load up the values into m2 from Model1
if(TryUpdateModel(m2)) //if it is ok (checks validation)
{
... your code...
}
I hope this helps.

Categories