I have an EF6 MVC app using Code First to generate the models. I am trying to create a mapping using AutoMapper between the model and a viewmodel representation of that model.
I don't have errors, but the resulting object is missing details for the PTCredential object. Specifically I am missing the PTCredential object that is nested within a PTCredential.
I don't believe the Ignores are causing this, but I can't pin it down. I have tried some suggestions from other posts on AutoMapper, but nothing has proven useful.
Could anyone provide some assistance on what I can do to successfully use AutoMapper in this situation?
Here is the code for how I am configuring and initializing the Mapper:
var pTConnections = _db.PTConnections.Include(p => p.PTConnectionClass).ToList();
Mapper.Initialize(cfg =>
{
cfg.CreateMap<PTConnection, PTConnectionViewModel>()
.AfterMap((s, d) => { foreach (var i in d.PTCredentialAssignments) i.PTConnection = d; });
cfg.CreateMap<PTCredentialAssignment, PTCredentialAssignmentViewModel>()
.ForMember(m => m.PTCredential, opt => opt.Ignore())
.ForMember(m => m.PTConnection, opt => opt.Ignore());
cfg.CreateMap<PTVendor, PTVendorViewModel>()
.ForMember(m => m.PTCredentials, opt => opt.Ignore())
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTCredential, PTCredentialViewModel>();
cfg.CreateMap<PTConnectionClass, PTConnectionClassViewModel>()
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTConnectionContactAssignment, PTConnectionContactAssignmentViewModel>()
.ForMember(m => m.PTConnection, opt => opt.Ignore());
});
var dest = Mapper.Map<List<PTConnection>, List<PTConnectionViewModel>>(pTConnections);
Here is my Code First Model:
public partial class PTConnection
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTConnection()
{
PTConnectionAssignments = new HashSet<PTConnectionAssignment>();
PTCredentialAssignments = new HashSet<PTCredentialAssignment>();
PTConnectionContactAssignments = new HashSet<PTConnectionContactAssignment>();
}
[Key]
public int PTCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(255)]
public string ConnectionName { get; set; }
[Required]
[StringLength(100)]
public string Host { get; set; }
public int Port { get; set; }
public string Comment { get; set; }
public int PTCCID { get; set; }
public bool? IsDisabled { get; set; }
public int PTVID { get; set; }
public virtual PTConnectionClass PTConnectionClass { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnectionAssignment> PTConnectionAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialAssignment> PTCredentialAssignments { get; set; }
public virtual PTVendor PTVendor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnectionContactAssignment> PTConnectionContactAssignments { get; set; }
}
public partial class PTCredential
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTCredential()
{
PTCredentialAssignments = new HashSet<PTCredentialAssignment>();
PTCredentialContactAssignments = new HashSet<PTCredentialContactAssignment>();
}
[Key]
public int PTCRID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(100)]
public string CredUsername { get; set; }
[Required]
[StringLength(500)]
public string CredPassword { get; set; }
public string Directory { get; set; }
public bool? IsDisabled { get; set; }
public string Comments { get; set; }
public int? PTVID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialAssignment> PTCredentialAssignments { get; set; }
public virtual PTVendor PTVendor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialContactAssignment> PTCredentialContactAssignments { get; set; }
}
public partial class PTVendor
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTVendor()
{
PTConnections = new HashSet<PTConnection>();
PTCredentials = new HashSet<PTCredential>();
PTIneligableCredentialVendorAssignments = new HashSet<PTIneligableCredentialVendorAssignment>();
PTVendorAssignments = new HashSet<PTVendorAssignment>();
PTVendorContactAssignments = new HashSet<PTVendorContactAssignment>();
}
[Key]
public int PTVID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50), Display(Name="Vendor Name")]
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnection> PTConnections { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredential> PTCredentials { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTIneligableCredentialVendorAssignment> PTIneligableCredentialVendorAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTVendorAssignment> PTVendorAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTVendorContactAssignment> PTVendorContactAssignments { get; set; }
}
[Table("PTCredentialAssignment")]
public partial class PTCredentialAssignment
{
[Key]
public int PTCRAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
public int PTCRID { get; set; }
public virtual PTConnection PTConnection { get; set; }
public virtual PTCredential PTCredential { get; set; }
}
[Table("PTConnectionClass")]
public partial class PTConnectionClass
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTConnectionClass()
{
PTConnections = new HashSet<PTConnection>();
}
[Key]
public int PTCCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50)]
public string Class { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnection> PTConnections { get; set; }
}
[Table("PTConnectionContactAssignment")]
public partial class PTConnectionContactAssignment
{
[Key]
public int PTCCAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
[Required]
[StringLength(60)]
public string FirstName { get; set; }
[Required]
[StringLength(60)]
public string LastName { get; set; }
[Required]
[StringLength(10)]
public string PhoneNumber { get; set; }
[StringLength(20)]
public string Extension { get; set; }
[StringLength(100)]
public string Email { get; set; }
[StringLength(60)]
public string Title { get; set; }
public string Comment { get; set; }
public virtual PTConnection PTConnection { get; set; }
}
Here is my ViewModel:
public partial class PTConnectionViewModel
{
[Key]
public int PTCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(255)]
public string ConnectionName { get; set; }
[Required]
[StringLength(100)]
public string Host { get; set; }
public int Port { get; set; }
public string Comment { get; set; }
public int PTCCID { get; set; }
public bool? IsDisabled { get; set; }
public int PTVID { get; set; }
public virtual PTConnectionClassViewModel PTConnectionClass { get; set; }
public virtual ICollection<PTConnectionAssignmentViewModel> PTConnectionAssignments { get; set; }
public virtual ICollection<PTCredentialAssignmentViewModel> PTCredentialAssignments { get; set; }
public virtual PTVendorViewModel PTVendor { get; set; }
public virtual ICollection<PTConnectionContactAssignmentViewModel> PTConnectionContactAssignments { get; set; }
}
public partial class PTVendorViewModel
{
[Key]
public int PTVID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50), Display(Name="Vendor Name")]
public string Name { get; set; }
public virtual ICollection<PTConnectionViewModel> PTConnections { get; set; }
public virtual ICollection<PTCredentialViewModel> PTCredentials { get; set; }
}
public partial class PTCredentialViewModel
{
[Key]
public int PTCRID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(100)]
public string CredUsername { get; set; }
[Required]
[StringLength(500)]
public string CredPassword { get; set; }
public string Directory { get; set; }
public bool? IsDisabled { get; set; }
public string Comments { get; set; }
public int? PTVID { get; set; }
public virtual ICollection<PTCredentialAssignmentViewModel> PTCredentialAssignments { get; set; }
public virtual PTVendorViewModel PTVendor { get; set; }
public virtual ICollection<PTCredentialContactAssignmentViewModel> PTCredentialContactAssignments { get; set; }
}
public partial class PTCredentialAssignmentViewModel
{
[Key]
public int PTCRAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
public int PTCRID { get; set; }
public virtual PTConnectionViewModel PTConnection { get; set; }
public virtual PTCredentialViewModel PTCredential { get; set; }
}
public partial class PTConnectionClassViewModel
{
[Key]
public int PTCCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50)]
public string Class { get; set; }
public virtual ICollection<PTConnectionViewModel> PTConnections { get; set; }
}
public partial class PTConnectionContactAssignmentViewModel
{
[Key]
public int PTCCAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
[Required]
[StringLength(60)]
public string FirstName { get; set; }
[Required]
[StringLength(60)]
public string LastName { get; set; }
[Required]
[StringLength(10)]
public string PhoneNumber { get; set; }
[StringLength(20)]
public string Extension { get; set; }
[StringLength(100)]
public string Email { get; set; }
[StringLength(60)]
public string Title { get; set; }
public string Comment { get; set; }
public virtual PTConnectionViewModel PTConnection { get; set; }
}
Here is the mapping that made my solution work:
cfg.CreateMap<PTConnection, PTConnectionViewModel>()
.AfterMap((s, d) => { foreach (var i in d.PTCredentialAssignments) i.PTConnection = d; });
cfg.CreateMap<PTCredentialAssignment, PTCredentialAssignmentViewModel>()
.ForMember(m => m.PTConnection, opt => opt.Ignore());
cfg.CreateMap<PTVendor, PTVendorViewModel>()
.ForMember(m => m.PTCredentials, opt => opt.Ignore())
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTCredential, PTCredentialViewModel>()
.ForMember(m => m.PTCredentialAssignments, opt => opt.Ignore())
.ForMember(m => m.PTCredentialContactAssignments, opt => opt.Ignore());
cfg.CreateMap<PTConnectionClass, PTConnectionClassViewModel>()
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTConnectionContactAssignment, PTConnectionContactAssignmentViewModel>()
.ForMember(m => m.PTConnection, opt => opt.Ignore());
Related
Working code - but it is not getting output what is the wrong in this code:
var result = _favouriteProjectRepository.Entity()
.Where(x => x.UserId == userId)
.Select(x => new FavouriteProject
{
ProjectId = x.ProjectId,
}).ToList();
var resultset = await _projectrepository.Entity()
.Where(x => (filters.FiscalYear == null ||
filters.FiscalYear.Contains(Convert.ToInt32(x.ContractNo.ToString().Substring(0, 2)))) &&
(filters.IsFavourite == false &&
result.Contains(x.Id).ToString()))
.Select(x => new Tests
{
Id = x.Id,
Name = x.Name,
AdvertisementStatusId = x.AdvertisementStatusId,
CreatedOn = x.CreatedOn,
ContractNo = x.ContractN0,
})
.OrderBy(x => x.Name)
.ToListAsync();
Models:-
public class FavouriteProject
{
public int ProjectId { get; set; }
public string UserId { get; set; }
public virtual Project Project { get; set; }
}
public class Tests
{
public int Id { get; set; }
public string Name { get; set; }
public int? ContractNo { get; set; }
public int? AdvertisementStatusId { get; set; }
public DateTime? CreatedOn { get; set; }
public virtual ICollection<FavouriteCompany> FavouriteCompany { get; set; }
}
**filters**
public class ProjectFilters
{
public List<int> FiscalYear { get; set; }
public bool IsFavourite { get; set; }
}
**Project Model**
public class Project
{
public int Id { get; set; }
public string ProcurmentNo { get; set; }
public int? ContractNo { get; set; }
public int? ProjectSizeId { get; set; }
public int? SelectionProcedureId { get; set; }
public int? ResponseRequestedId { get; set; }
public int? AdvertisementStatusId { get; set; }
public int? NoOfPages { get; set; }
public string PreQualificationRequirements { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public string MultilineDescription { get; set; }
public string BridgDesignWorkType { get; set; }
public string DbeMbeRequirements { get; set; }
public string SpecialNote { get; set; }
public decimal? BudgetAmount { get; set; }
public decimal? EstimatedContractAmount { get; set; }
public decimal? MaxumumContractAmount { get; set; }
public bool? IsMultipleContracts { get; set; }
public string ProposedScopeLoc { get; set; }
public string BondingRequirements { get; set; }
public string TechQuestionsAddressedTo { get; set; }
public int Status { get; set; }
public int? DistrictId { get; set; }
public DateTime? CreatedOn { get; set; }
public string ResponseEmail { get; set; }
public string ViewRFP { get; set; }
public string AdditionalInformation { get; set; }
public string LowBidDesign { get; set; }
public string AdminNote { get; set; }
public string MeetingLocationNotes { get; set; }
public string FdotKey { get; set; }
//public DateTime? EventDate { get; set; }
public bool IsUpdatesLocked { get; set; }
public bool? BdiProjectIndicator { get; set; }
public string LiabilityInsurance { get; set; }
public string ProjectThreshold { get; set; }
public int NumberOfContracts { get; set; }
public int? RelatedProjectCount { get; set; }
public string AdvertisementSpecialNotes { get; set; }
public string FMNSpecialNotes { get; set; }
public virtual ProjectSize ProjectSize { get; set; }
public virtual SelectionProcedure SelectionProcedure { get; set; }
public virtual ResponseRequested ResponseRequested { get; set; }
public virtual AdvertisementStatus AdvertisementStatus { get; set; }
public virtual District District { get; set; }
public virtual ICollection<ProjectEvent> ProjectEvents { get; set; }
public virtual ICollection<FinancialManagementNumber> FinancialManagementNumbers { get; set; }
public virtual ICollection<ProjectWorkGroup> ProjectWorkGroups { get; set; }
public virtual ICollection<ScrapedLink> ScrapedLinks { get; set; }
public virtual ICollection<ProjectStandardNote> ProjectStandardNotes { get; set; }
public virtual ICollection<FtpFileProject> FtpFileProjects { get; set; }
public virtual ICollection<CompanyProject> CompanyProjects { get; set; }
public virtual ICollection<ContactProject> ContactProjects { get; set; }
public virtual ICollection<ProjectUnderUtilizedWorkGroup> ProjectUnderUtilizedWorkGroups { get; set; }
public virtual ICollection<WorkProgram> WorkPrograms { get; set; }
[NotMapped]
public virtual ICollection<ScrapedProjectModel> ScrapedProjects { get; set; }
// public virtual FavouriteProject FavouriteProject { get; set; }
Can anyone give me simplified query to call both in single request?
And I have added my models and filters you can go through it I have used only one filters and the model of project because in that class only I have mentioned
Try the following query:
var query = _projectrepository.Entity().AsQueryable();
if (filters.FiscalYear?.Count > 0)
{
query = query.Where(x => filters.FiscalYear.Contains(Convert.ToInt32(x.ContractNo.ToString().Substring(0, 2))));
}
if (filters.IsFavourite)
{
var favouriteProjects = _favouriteProjectRepository.Entity()
.Where(x => x.UserId == userId);
query =
from p in query
join f in favouriteProjects on p.Id equals f.ProjectId
select p;
}
var resultset = await query
.Select(x => new Tests
{
Id = x.Id,
Name = x.Name,
AdvertisementStatusId = x.AdvertisementStatusId,
CreatedOn = x.CreatedOn,
ContractNo = x.ContractN0,
})
.OrderBy(x => x.Name)
.ToListAsync();
I am trying to connect two tables with a code first migration. I thought EF would create many to many relationship table itself but I get error "build failed". While building whole project everything works fine. It's just the migration.
Following are my models -
Task:
[Key]
public int Id { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? EndedAt { get; set; }
[Column(TypeName = "text")]
public string CreatedBy { get; set; }
[Required]
[Column(TypeName = "text")]
public string Title { get; set; }
[Required]
[Column(TypeName = "text")]
public string Description { get; set; }
public virtual TaskGroups TaskGroup { get; set; }
public string Status { get; set; }
[Column(TypeName = "text")]
public string WantedUser { get; set; }
TaskGroup:
[Required]
public int Id { get; set; }
[Required]
public string GroupName { get; set; }
public virtual Tasks Tasks { get; set; }
At first I've tried with ICollection<> but I got the same error.
My project is .Net Core 3.
Any ideas?
Edit
Tasks
[Key]
public int Id { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? EndedAt { get; set; }
[Column(TypeName = "text")]
public string CreatedBy { get; set; }
[Required]
[Column(TypeName = "text")]
public string Title { get; set; }
[Required]
[Column(TypeName = "text")]
public string Description { get; set; }
public string Status { get; set; }
[Column(TypeName = "text")]
public string WantedUser { get; set; }
public IList<TaskGroupTask> TaskGroupTask { get; set; }
TaskGroups
[Key]
public int Id { get; set; }
[Required]
public string GroupName { get; set; }
public IList<TaskGroupTask> { get; set; }
TaskGroupTask
public int TaskId { get; set; }
public int TaskGroupId { get; set; }
public Tasks Tasks { get; set; }
public TaskGroups TaskGroups { get; set; }
DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<TaskGroupTask>(e =>
{
e.HasKey(p => new { p.TaskId, p.TaskGroupId });
e.HasOne(p => p.Tasks).WithMany(t =>
t.TaskGroupTask).HasForeignKey(p => p.TaskId);
e.HasOne(p => p.TaskGroups).WithMany(tg =>
tg.TaskGroupTask).HasForeignKey(p => p.TaskGroupId);
});
}
public DbSet<TaskGroupTask> TaskGroupTask { get; set; }
You will need to create a joining entity, like MyJoiningEntity or TaskGroupTask, whose sole purpose is to create a link between Task and TaskGroup. Following models should give you the idea -
public class Task
{
public int Id { get; set; }
public string Description { get; set; }
public IList<JoiningEntity> JoiningEntities { get; set; }
}
public class TaskGroup
{
public int Id { get; set; }
public string GroupName { get; set; }
public IList<JoiningEntity> JoiningEntities { get; set; }
}
// this is the Joining Entity that you need to create
public class JoiningEntity
{
public int TaskId { get; set; }
public int TaskGroupId { get; set; }
public Task Task { get; set; }
public TaskGroup TaskGroup { get; set; }
}
Then you can configure the relation in the OnModelCreating method of your DbContext class, like -
modelBuilder.Entity<JoiningEntity>(e =>
{
e.HasKey(p => new { p.TaskId, p.TaskGroupId });
e.HasOne(p => p.Task).WithMany(t => t.JoiningEntities).HasForeignKey(p => p.TaskId);
e.HasOne(p => p.TaskGroup).WithMany(tg => tg.JoiningEntities).HasForeignKey(p => p.TaskGroupId);
});
This will define a composite primary key on JoiningEntity table based on the TaskId and TaskGroupId properties. Since this table's sole purpose is to link two other tables, it doesn't actually need it's very own Id field for primary key.
Note: This approach is for EF versions less than 5.0. From EF 5.0 you can create a many-to-many relationship in a more transparent way.
Since I have some time, I've decided to pull all pices of the code in one place. I think it would be very usefull sample how to create code-first many-to-many relations for database tables. This code was tested in Visual Studio and a new database was created without any warnings:
public class Task
{
public Task()
{
TaskTaskGroups = new HashSet<TaskTaskGroup>();
}
[Key]
public int Id { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? EndedAt { get; set; }
[Column(TypeName = "text")]
public string CreatedBy { get; set; }
[Required]
[Column(TypeName = "text")]
public string Title { get; set; }
[Required]
[Column(TypeName = "text")]
public string Description { get; set; }
public string Status { get; set; }
[Column(TypeName = "text")]
public string WantedUser { get; set; }
[InverseProperty(nameof(TaskTaskGroup.Task))]
public virtual ICollection<TaskTaskGroup> TaskTaskGroups { get; set; }
}
public class TaskGroup
{
public TaskGroup()
{
TaskTaskGroups = new HashSet<TaskTaskGroup>();
}
[Required]
public int Id { get; set; }
[Required]
public string GroupName { get; set; }
[InverseProperty(nameof(TaskTaskGroup.TaskGroup))]
public virtual ICollection<TaskTaskGroup> TaskTaskGroups { get; set; }
}
public class TaskTaskGroup
{
[Key]
public int Id { get; set; }
public int TaskId { get; set; }
[ForeignKey(nameof(TaskId))]
[InverseProperty(nameof(TaskTaskGroup.Task.TaskTaskGroups))]
public virtual Task Task { get; set; }
public int TaskGroupId { get; set; }
[ForeignKey(nameof(TaskGroupId))]
[InverseProperty(nameof(TaskTaskGroup.Task.TaskTaskGroups))]
public virtual TaskGroup TaskGroup { get; set; }
}
public class TaskDbContext : DbContext
{
public TaskDbContext()
{
}
public TaskDbContext(DbContextOptions<TaskDbContext> options)
: base(options)
{
}
public DbSet<Task> Tasks { get; set; }
public DbSet<TaskGroup> TaskGroups { get; set; }
public DbSet<TaskTaskGroup> TaskTaskGroups { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=localhost;Database=Task;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TaskTaskGroup>(entity =>
{
entity.HasOne(d => d.Task)
.WithMany(p => p.TaskTaskGroups)
.HasForeignKey(d => d.TaskId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_TaskTaskGroup_Task");
entity.HasOne(d => d.TaskGroup)
.WithMany(p => p.TaskTaskGroups)
.HasForeignKey(d => d.TaskGroupId)
.HasConstraintName("FK_TaskTaskGroup_TaskCroup");
});
}
}
I have an EF6 MVC app using Code First to generate the models. I am trying to create a mapping using AutoMapper between the model and a view model representation of that model. However, when I do the mapping I receive the error:
Mapper not initialized. Call Initialize with appropriate
configuration. If you are trying to use mapper instances through a
container or otherwise, make sure you do not have any calls to the
static Mapper.Map methods, and if you're using ProjectTo or
UseAsDataSource extension methods, make sure you pass in the
appropriate IConfigurationProvider instance.
I am definitely initializing the Mapper, but I am not able to figure out why the configuration is failing. Could anyone provide some assistance on what I can do to successfully use AutoMapper in this situation?
Here is the code for how I am configuring and initializing the Mapper:
var pTConnections = _db.PTConnections.Include(p => p.PTConnectionClass).ToList();
Mapper.Initialize(cfg =>
{
cfg.CreateMap<PTConnection, PTConnectionViewModel>()
.AfterMap((s, d) => { foreach (var i in d.PTCredentialAssignments) i.PTConnection = d; });
cfg.CreateMap<PTCredentialAssignment, PTCredentialAssignmentViewModel>()
.ForMember(m => m.PTCredential, opt => opt.Ignore())
.ForMember(m => m.PTConnection, opt => opt.Ignore());
cfg.CreateMap<PTVendor, PTVendorViewModel>()
.ForMember(m => m.PTCredentials, opt => opt.Ignore())
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTCredential, PTCredentialViewModel>();
cfg.CreateMap<PTConnectionClass, PTConnectionClassViewModel>()
.ForMember(m => m.PTConnections, opt => opt.Ignore());
cfg.CreateMap<PTConnectionContactAssignment, PTConnectionContactAssignmentViewModel>()
.ForMember(m => m.PTConnection, opt => opt.Ignore());
});
var dest = Mapper.Map<List<PTConnection>, List<PTConnectionViewModel>>(pTConnections);
Here is my Code First Model:
public partial class PTConnection
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTConnection()
{
PTConnectionAssignments = new HashSet<PTConnectionAssignment>();
PTCredentialAssignments = new HashSet<PTCredentialAssignment>();
PTConnectionContactAssignments = new HashSet<PTConnectionContactAssignment>();
}
[Key]
public int PTCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(255)]
public string ConnectionName { get; set; }
[Required]
[StringLength(100)]
public string Host { get; set; }
public int Port { get; set; }
public string Comment { get; set; }
public int PTCCID { get; set; }
public bool? IsDisabled { get; set; }
public int PTVID { get; set; }
public virtual PTConnectionClass PTConnectionClass { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnectionAssignment> PTConnectionAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialAssignment> PTCredentialAssignments { get; set; }
public virtual PTVendor PTVendor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnectionContactAssignment> PTConnectionContactAssignments { get; set; }
}
public partial class PTCredential
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTCredential()
{
PTCredentialAssignments = new HashSet<PTCredentialAssignment>();
PTCredentialContactAssignments = new HashSet<PTCredentialContactAssignment>();
}
[Key]
public int PTCRID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(100)]
public string CredUsername { get; set; }
[Required]
[StringLength(500)]
public string CredPassword { get; set; }
public string Directory { get; set; }
public bool? IsDisabled { get; set; }
public string Comments { get; set; }
public int? PTVID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialAssignment> PTCredentialAssignments { get; set; }
public virtual PTVendor PTVendor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredentialContactAssignment> PTCredentialContactAssignments { get; set; }
}
public partial class PTVendor
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTVendor()
{
PTConnections = new HashSet<PTConnection>();
PTCredentials = new HashSet<PTCredential>();
PTIneligableCredentialVendorAssignments = new HashSet<PTIneligableCredentialVendorAssignment>();
PTVendorAssignments = new HashSet<PTVendorAssignment>();
PTVendorContactAssignments = new HashSet<PTVendorContactAssignment>();
}
[Key]
public int PTVID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50), Display(Name="Vendor Name")]
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnection> PTConnections { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTCredential> PTCredentials { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTIneligableCredentialVendorAssignment> PTIneligableCredentialVendorAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTVendorAssignment> PTVendorAssignments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTVendorContactAssignment> PTVendorContactAssignments { get; set; }
}
[Table("PTCredentialAssignment")]
public partial class PTCredentialAssignment
{
[Key]
public int PTCRAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
public int PTCRID { get; set; }
public virtual PTConnection PTConnection { get; set; }
public virtual PTCredential PTCredential { get; set; }
}
[Table("PTConnectionClass")]
public partial class PTConnectionClass
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PTConnectionClass()
{
PTConnections = new HashSet<PTConnection>();
}
[Key]
public int PTCCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50)]
public string Class { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PTConnection> PTConnections { get; set; }
}
[Table("PTConnectionContactAssignment")]
public partial class PTConnectionContactAssignment
{
[Key]
public int PTCCAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
[Required]
[StringLength(60)]
public string FirstName { get; set; }
[Required]
[StringLength(60)]
public string LastName { get; set; }
[Required]
[StringLength(10)]
public string PhoneNumber { get; set; }
[StringLength(20)]
public string Extension { get; set; }
[StringLength(100)]
public string Email { get; set; }
[StringLength(60)]
public string Title { get; set; }
public string Comment { get; set; }
public virtual PTConnection PTConnection { get; set; }
}
Here is my ViewModel:
public partial class PTConnectionViewModel
{
[Key]
public int PTCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(255)]
public string ConnectionName { get; set; }
[Required]
[StringLength(100)]
public string Host { get; set; }
public int Port { get; set; }
public string Comment { get; set; }
public int PTCCID { get; set; }
public bool? IsDisabled { get; set; }
public int PTVID { get; set; }
public virtual PTConnectionClassViewModel PTConnectionClass { get; set; }
public virtual ICollection<PTConnectionAssignmentViewModel> PTConnectionAssignments { get; set; }
public virtual ICollection<PTCredentialAssignmentViewModel> PTCredentialAssignments { get; set; }
public virtual PTVendorViewModel PTVendor { get; set; }
public virtual ICollection<PTConnectionContactAssignmentViewModel> PTConnectionContactAssignments { get; set; }
}
public partial class PTVendorViewModel
{
[Key]
public int PTVID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50), Display(Name="Vendor Name")]
public string Name { get; set; }
public virtual ICollection<PTConnectionViewModel> PTConnections { get; set; }
public virtual ICollection<PTCredentialViewModel> PTCredentials { get; set; }
}
public partial class PTCredentialViewModel
{
[Key]
public int PTCRID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(100)]
public string CredUsername { get; set; }
[Required]
[StringLength(500)]
public string CredPassword { get; set; }
public string Directory { get; set; }
public bool? IsDisabled { get; set; }
public string Comments { get; set; }
public int? PTVID { get; set; }
public virtual ICollection<PTCredentialAssignmentViewModel> PTCredentialAssignments { get; set; }
public virtual PTVendorViewModel PTVendor { get; set; }
public virtual ICollection<PTCredentialContactAssignmentViewModel> PTCredentialContactAssignments { get; set; }
}
public partial class PTCredentialAssignmentViewModel
{
[Key]
public int PTCRAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
public int PTCRID { get; set; }
public virtual PTConnectionViewModel PTConnection { get; set; }
public virtual PTCredentialViewModel PTCredential { get; set; }
}
public partial class PTConnectionClassViewModel
{
[Key]
public int PTCCID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
[Required]
[StringLength(50)]
public string Class { get; set; }
public virtual ICollection<PTConnectionViewModel> PTConnections { get; set; }
}
public partial class PTConnectionContactAssignmentViewModel
{
[Key]
public int PTCCAID { get; set; }
[Column(TypeName = "datetime2")]
public DateTime ModifiedDate { get; set; }
[Required]
[StringLength(500)]
public string ModifiedBy { get; set; }
public int PTCID { get; set; }
[Required]
[StringLength(60)]
public string FirstName { get; set; }
[Required]
[StringLength(60)]
public string LastName { get; set; }
[Required]
[StringLength(10)]
public string PhoneNumber { get; set; }
[StringLength(20)]
public string Extension { get; set; }
[StringLength(100)]
public string Email { get; set; }
[StringLength(60)]
public string Title { get; set; }
public string Comment { get; set; }
public virtual PTConnectionViewModel PTConnection { get; set; }
}
Just create the map from one type to another. Don't create the map from a List of one type to a list of another type. Automapper can automatically handle collections.
In effect, you're telling Automapper how to map a List<A> to a List<B> without telling Automapper how to actually map A to B. Change your registration to the following:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<PTConnection, PTConnectionViewModel>();
});
You can still map a List<PTConnection> to a List<PTConnectionViewModel> just fine, as well as most other collection types.
I have 2 classes, course and student, and I want to get student courses with student id
help me please
I'm using entity framework code first
public class Course {
public int CourseID { get; set; }
public string Title { get; set; }
public string Details { get; set; }
public string img { get; set; }
public DateTime DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public int SubCategoryID { get; set; }
public string Code { get; set; }
public string Summury { get; set; }
public decimal Price { get; set; }
public bool IsGift { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
public ICollection<Student> Students { get; set; }
}
public class Student {
[Key]
public int StudentID { get; set; }
public string Name { get; set; }
public DateTime? DateBirth { get; set; }
public int? Age { get; set; }
public int? Sex { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Mobile2 { get; set; }
public string UniversityID { get; set; }
public string CollegeID { get; set; }
public string IdentityID { get; set; }
public string Address { get; set; }
public string Education { get; set; }
public decimal? Payments { get; set; }
public string HowToKnow { get; set; }
public DateTime? GradeDate { get; set; }
public string LaterCourses { get; set; }
public string Job { get; set; }
public string Specialist { get; set; }
public string Notes { get; set; }
public int StatueID { get; set; }
public Guid? UserID { get; set; }
public DateTime? DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
public virtual IList<Course> Courses { get; set; }
}
I want to get all courses for a given StudentID using a lambda expression.
var students = repository.Query<Course>(c => c.Student.Any(st=>st.StudentID == StudentID)
I have two objects like:
public class Area : IEntity
{
public virtual int Id { get; set; }
public virtual int AreaTypeLookupId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public virtual string Name { get; set; }
[Column(TypeName = "varchar")]
[StringLength(2)]
public virtual string VMRegionCode { get; set; }
public virtual int GISPrimaryKeyId { get; set; }
public virtual string ConcatenatedGISAreaIds { get; set; }
public virtual int? ParentAreaId { get; set; }
public virtual int? ParentRegionAreaId { get; set; }
[Column(TypeName = "char")]
[StringLength(3)]
public virtual string CostCenterCode { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
// Navigation properties
public virtual AreaTypeLookup AreaTypeLookup { get; set; }
}
public class AreaTypeLookup : IEntity
{
[Column("Id")]
public virtual int AreaTypeLookupId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public virtual string Name { get; set; }
[Column(TypeName = "varchar")]
[StringLength(10)]
public virtual string ShortName { get; set; }
public virtual int? AreaTypeLevelLookupId { get; set; }
public virtual int? OperationTypeLookupId { get; set; }
public virtual int? ParentAreaTypeLookupId { get; set; }
public bool IsAvailableToSetBudgetAgainst { get; set; }
public int DisplaySortOrder { get; set; }
public bool IsProtected { get; set; }
public DateTime? DeletedDateTime { get; set; }
public int? ManagedByServiceTypeLookupId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
}
What I want is to get all the areas where areatypelookupid = 3. For this area type the name is "region"
What is the best way to get the areas for code maintainability:
This:
var areas = _unitOfWork.AreaRepository.GetAll().Where(x => x.AreaTypeLookupId == 3);
or this:
var areas = _unitOfWork.AreaRepository.GetAll().Where(x => x.AreaTypeLookup.Name == "region");
where I guess "region" should really becoming from a resources file.
Typically, you will want to use the primary key as that should be immutable. However, if you can guarantee that the lookup name is not going to change, then searching by name would be tolerable. The reason I say tolerable is because running queries off of the primary key will be more efficient on the database, on top of the immutability.