asp.net mvc automapping view model to domain model - asp.net-mvc

Is it possible to automap UserViewModel to User?
public class User
{
[Key]
public virtual int UserId { get; set; }
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
[Required]
public virtual string Username { get; set; }
[Required]
public virtual string Password { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class UserViewModel
{
public User User { get; set; }
public List<Role> AvailableRoles { get; set; }
public List<Role> AssignedRoles { get; set; }
public int[] AvailableSelected { get; set; }
public int[] AssignedSelected { get; set; }
public string SavedAssigned { get; set; }
}
AutoMapper.Mapper.CreateMap<UserViewModel, User>();
AutoMapper.Mapper.Map(model, user);
I've tried this, but it won't work. I need it for my Edit action method in the User controller to save the changes to the database.

Have you tried
AutoMapper.Mapper.CreateMap<UserViewModel, User>()
.ForMember(dest => dest, opt => opt.MapFrom(src => src.User));

Related

Rename column in derived class using Entity Framework

I have asked question in a different post, but seems that was not the right question, so going to reword here:
I have three classes:
public class StateLog : BaseModel
{
public Guid StateLogId { get; set; }
public Guid LookupMasterId { get; set; }
public Guid EntityId { get; set; }
public string Discriminator { get; set; }
public bool IsActive { get; set; }
public virtual LookupMaster State { get; set; }
}
Second class:
public class ApplicationState : StateLog
{
[Column("EntityId")]
public Guid ApplicationId { get; set; }
}
There is another Class DocumentStates which inherits from StateLog.
Application:
public class Application : BaseModel
{
public Guid ApplicationId { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
[Required]
public Guid ApplicationTypeId { get; set; }
public bool? AuthorizedToWork { get; set; } = false;
public string Token { get; set; }
public string ApplicationTitle { get; set; }
public string WorkStartDate { get; set; }
public Nullable<DateTime> SignedAt { get; set; } = DateTime.Now;
public bool? Signed { get; set; }
public string Notes { get; set; }
public virtual ICollection<ApplicationSelfDeclaration> ApplicationSelfDeclarations { get; set; }
public virtual ICollection<ApplicationState> ApplicationStates { get; set; }
public virtual ICollection<StateLog> StateLogs { get; set; }
}
I am trying to save statelogs for both application and documents in same table and based on Discriminator, fetch data.
E.g.
_context.Applications.include(a => a.ApplicationState)
This is not not working. ApplicationState should Alias EntityId column as ApplicationId. But it is not working.
Any idea what my options are at this point?
Thanks in advance.

Renaming default table names in asp.net mvc project without breaking foreign keys

I Created a new MVC 5 project whenever i try to rename the table names as described in this question
Change table names using the new Identity system
It always breaks the foreign key relationships in the Logins, Claims, Roles tables.
I have tried to override the OnModelCreating method but in vein here is my code
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
modelBuilder.Entity<App>().HasKey(m => new { m.AppId, m.FacebookId });
modelBuilder.Entity<IdentityUser>().ToTable("Admins");
modelBuilder.Entity<IdentityUser>().
Property(p => p.Id).HasColumnName("AdminId");
modelBuilder.Entity<Admin>()
.ToTable("Admins")
.Property(p => p.Id).HasColumnName("AdminId");
modelBuilder.Entity<IdentityUserLogin>().ToTable("Logins")
.HasKey(m => new { m.ProviderKey, m.UserId, m.LoginProvider })
.Property(m => m.UserId)
.HasColumnName("AdminId");
modelBuilder.Entity<IdentityUserRole>().ToTable("AdminRoles")
.HasKey(m => new { m.RoleId, m.UserId })
.Property(m => m.RoleId)
.HasColumnName("AdminRoleId");
modelBuilder.Entity<IdentityUserRole>().Property(m => m.UserId)
.HasColumnName("AdminId");
//modelBuilder.Entity<IdentityUserRole>().HasRequired(m => m.UserId);
//modelBuilder.Entity<IdentityUserLogin>().HasRequired(m => m.UserId);
modelBuilder.Entity<IdentityUserClaim>().ToTable("Claims")
.HasKey(m=> m.Id)
.Property(m => m.Id)
.HasColumnName("ClaimId");
modelBuilder.Entity<IdentityRole>().ToTable("Roles")
.HasKey(m => m.Id).Property(m => m.Id).HasColumnName("RoleId");
}
where the "Admin" Class is my name for the ApplicationUser Default class plus my own implementation of it
public class Admin : IdentityUser
{
[Required]
public virtual List<App> Apps { get; set; }
public bool? IsPremium { get; set; }
[DataType(DataType.Date)]
public DateTime? LastPublishDateTime { get; set; }
}
here are my other domain classes
public class App
{
[Key]
[Column("AppId", Order = 1)]
public virtual int AppId { get; set; }
[Required]
[Key]
[Column("FacebookId", Order = 2)]
public virtual string FacebookId { get; set; }
[Required]
public virtual string Secret { get; set; }
public virtual List<User> Users { get; set; }
public virtual List<Post> Posts { get; set; }
[Required]
public virtual Admin Admin { get; set; }
}
public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int PostId { get; set; }
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual string Link { get; set; }
public virtual string Image { get; set; }
public virtual bool IsSpecial { get; set; }
[Required]
public virtual App App { get; set; }
[Required]
public virtual DateTime? PublishDate { get; set; }
}
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int UserId { get; set; }
[MaxLength(500)]
public virtual string FacebookId { get; set; }
[MaxLength(500)]
public virtual string Token { get; set; }
[Required]
public virtual App App { get; set; }
}

Entity Framework Fluent API

My Entities are as follows...
public class Project{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey{
public int Id { get; set; }
public int ProjectId { get; set; }
public string Name { get; set; }
public virtual Project Project { get; set; }
}
public class Category{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class SurveyCategory{
public int Id { get; set; }
public int SurveyId{ get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual Survey Survey { get; set; }
public virtual Category Category { get; set; }
}
A project will have list of Surveys, A Survey will have only one Category, A Category can have multiple Survey, SurveyCategory is the table where I am storing Survey + Category link.
Can anyone direct me to what would be appropriate Fluent API code will be for this to map properly.... So far I have this....
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Project>().HasMany(project => project.Surveys);}
hi I hope I understood what you are looking for.
First of al you should do a few changes to your model
public class Project
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey
{
public int Id { get; set; }
public int ProjectId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual Project Project { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<SurveyCategory> SurveyCategory { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
public virtual ICollection<SurveyCategory> SurveyCategory { get; set; }
}
public class SurveyCategory
{
public int Id { get; set; }
public string Name { get; set; }
public int SurveyId { get; set; }
public virtual Survey Survey { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
And then on the model creating you should do this
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.HasMany(p => p.Surveys)
.WithRequired(u => u.Project);
modelBuilder.Entity<Category>()
.HasMany(p => p.Surveys)
.WithRequired(u => u.Category);
modelBuilder.Entity<Category>()
.HasMany(p => p.SurveyCategory)
.WithRequired(u => u.Category)
.HasForeignKey(k => k.CategoryId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Survey>()
.HasMany(p => p.SurveyCategory)
.WithRequired(u => u.Survey)
.HasForeignKey(k => k.SurveyId)
.WillCascadeOnDelete(false);
}
I hope this helps

Entity Framework Many to Many Cascade Delete Issue

Having a strange issue working on a code first EF project.
I have the following entities:
public class Booking
{
public Guid BookingId { get; set; }
public virtual List<AccountingDocumentItem> AccountingDocumentItems { get; set; }
}
public class AccountingDocumentItem
{
public Guid AccountingDocumentItemId { get; set; }
public virtual List<Employee> Employees { get; set; }
public virtual List<Booking> Bookings { get; set; }
}
public class Employee
{
public Guid EmployeeId { get; set; }
public string Name { get; set; }
public virtual List<AccountingDocumentItem> AccountingDocumentItems { get; set; }
}
As you can see, there is meant to be many-to-many relationship between AccountingDocumentItem and both Bookings and Employees. When configuring my AccountingDocumentItem I use the following:
public AccountingDocumentItemConfiguration()
{
HasMany(x => x.Employees);
HasMany(x => x.Bookings);
}
What is strange is that this works perfectly for Employees. I get a AccountingDocumentItemEmployees table created. But for Bookings I get the following error:
"Introducing FOREIGN KEY constraint 'FK_dbo.AccountingDocumentItemBookings_dbo.Bookings_Booking_BookingId' on table 'AccountingDocumentItemBookings' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints."
Now I've tried to do this along the lines of below code:
HasMany(x => x.Bookings).WithMany(b => b.AccountingDocumentItems)...
But I only get the option to do a Map using the above line, no option to do a WillCascadeOnDelete(false).
Can someone point out what I'm doing wrong, because comparing it to how I handle Employees I can't see any difference.
EDIT:
My original post abbreviated the entities, which is probably where the problem is arising. Here is the full entity:
public class AccountingDocument
{
public Guid AccountingDocumentId { get; set; }
public Guid SiteId { get; set; }
public virtual Site Site { get; set; }
public Guid? ClientId { get; set; }
public virtual Client Client { get; set; }
public Guid? SupplierId { get; set; }
public virtual Supplier Supplier { get; set; }
public string DocumentNumber { get; set; }
public string Reference { get; set; }
public string Description { get; set; }
public string Notes { get; set; }
public Guid LinkedAccountingDocumentId { get; set; }
public virtual AccountingDocument LinkedAccountingDocument { get; set; }
public byte AccountingDocumentTypeId { get; set; }
public DateTime CreationDate { get; set; }
public DateTime DocumentDate { get; set; }
public decimal Total { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
public string Room { get; set; }
public virtual List<AccountingDocumentItem> AccountingDocumentItems { get; set; }
}
public class AccountingDocumentItem
{
public Guid AccountingDocumentItemId { get; set; }
public Guid AccountingDocumentId { get; set; }
public virtual AccountingDocument AccountingDocument { get; set; }
public string Description { get; set; }
public Guid TaxId { get; set; }
public virtual Tax Tax { get; set; }
public decimal Quantity { get; set; }
public string Unit { get; set; }
public decimal Cost { get; set; }
public decimal SellInclusive { get; set; }
public decimal SellExclusive { get; set; }
public decimal DiscountPercentage { get; set; }
public decimal TotalInclusive { get; set; }
public decimal TotalExclusive { get; set; }
public decimal CommissionInclusive { get; set; }
public decimal CommissionExclusive { get; set; }
public int LoyaltyPoints { get; set; }
public bool IsSeries { get; set; }
public byte ItemType { get; set; }
public Guid? ServiceId { get; set; }
public virtual Service Service { get; set; }
public Guid? ProductId { get; set; }
public virtual Product Product { get; set; }
public Guid? VoucherId { get; set; }
public virtual Voucher Voucher { get; set; }
public int SortOrder { get; set; }
public Guid? SourceId { get; set; }
public virtual Source Source { get; set; }
public Guid? CostCentreId { get; set; }
public virtual CostCentre CostCentre { get; set; }
public Guid? ClientId { get; set; }
public virtual Client Client { get; set; }
public Guid PackageGroupId { get; set; }
public Guid PackageServiceId { get; set; }
public virtual List<Employee> Employees { get; set; }
public virtual List<Booking> Bookings { get; set; }
public virtual List<MedicalDiagnosis> MedicalDiagnoses { get; set; }
}
public class Booking
{
public Guid BookingId { get; set; }
public Guid SiteId { get; set; }
public Site Site { get; set; }
public Guid? ClientId { get; set; }
public Client Client { get; set; }
public Guid BookingStateId { get; set; }
public BookingState BookingState { get; set; }
public virtual List<AccountingDocumentItem> AccountingDocumentItems { get; set; }
}
And my configuration:
public class AccountingDocumentConfiguration : EntityTypeConfiguration<AccountingDocument>
{
public AccountingDocumentConfiguration()
{
Property(x => x.Reference).HasMaxLength(200);
HasRequired(x => x.Site);
Property(x => x.DocumentNumber).IsRequired().HasMaxLength(100);
Property(x => x.Reference).HasMaxLength(200);
Property(x => x.Description).HasMaxLength(500);
Property(x => x.Notes).HasMaxLength(500);
HasOptional(x => x.LinkedAccountingDocument);
Property(x => x.AccountingDocumentTypeId).IsRequired();
Property(x => x.CreationDate).IsRequired();
Property(x => x.DocumentDate).IsRequired();
Property(x => x.Total).IsRequired();
Property(x => x.Room).HasMaxLength(50);
}
}
public class AccountingDocumentItemConfiguration : EntityTypeConfiguration<AccountingDocumentItem>
{
public AccountingDocumentItemConfiguration()
{
Property(x => x.Description).IsRequired().HasMaxLength(200);
HasMany(x => x.Employees);
HasMany(x => x.Bookings);
HasMany(x => x.MedicalDiagnoses);
Property(x => x.Unit).HasMaxLength(50);
}
}
Even with the added text above it's working for me, once I comment out the added nav properties that aren't fully defined above. The FK error means that there might be a race condition if you happen to delete (See this article), but with whats here I can't tell. Do you need to have cascading deletes on your database? If not, you could just turn it off - I realize it's a pretty broad stroke on a minor problem though.
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
If this is not an option - it's something else that you haven't included. Do you have mappings for the Bookings table? It looks like Bookings have a required Site - is it possible that deleting a site, could trigger a delete in a bunch of other things? It looks like Site could do something like this Site -> Account Document -> Accounting Document item.. Site -> Booking possibly?
Here's another SO question that could possibly be related.

multiple "1 to 0..1" relationship models

I am using this tutorial from microsoft to create a one-zero-to-one relationship with EF4.1 Between an Instructor and OfficeAssignment. This is working like a charm.
But now I want to add a Home for each Instructor (1 to zero-or-1) like in this:
I added the Home model exactly the same way as the OfficeAssignment (like in the tutorial above), but when I try to add controllers for these model, I get the error "An item with the same name has already been added".
So my model is set up incorrectly.
What is wrong with the below?
How do I create multiple one-to-zero-to-one relationships in EF4.1?
public class Instructor
{
public Int32 InstructorID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
public virtual Home Home { get; set; }
}
public class OfficeAssignment
{
[Key]
public int InstructorID { get; set; }
public string Location { get; set; }
public virtual Instructor Instructor { get; set; }
}
public class Home
{
[Key]
public int InstructorID { get; set; }
public string Location { get; set; }
public virtual Instructor Instructor { get; set; }
}
public class Context : DbContext
{
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
public DbSet<Instructor> Instructors { get; set; }
public DbSet<Home> Homes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Instructor>()
.HasOptional(p => p.OfficeAssignment)
.WithRequired(p => p.Instructor);
modelBuilder.Entity<Instructor>()
.HasOptional(p => p.Home).WithRequired(p => p.Instructor);
}
Doesn't look like EF supports real 1 to 0..1 relationship. You need a foreign key. And add the optional (int?) into the main model.
So I did this as follow, and it works like a charm.
public class Instructor
{
public Int InstructorID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public int? OfficeAssignmentID { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
public int? HomeID { get; set; }
public virtual Home Home { get; set; }
}
public class OfficeAssignment
{
public int OfficeAssignmentID { get; set; }
public string Location { get; set; }
}
public class Home
{
public int HomeID { get; set; }
public string Location { get; set; }
}

Resources