I have a ClientDocument data model and mapping as follows:
public class ClientDocument : BaseEntity
{
public int DocumentOwnerId { get; set; }
public int ClientProfileId { get; set; }
public virtual ClientProfile ClientProfile { get; set; }
public int DocumentId { get; set; }
public virtual Document Document { get; set; }
}
public ClientDocumentMap(EntityTypeBuilder<ClientDocument> entityBuilder)
{
entityBuilder.HasKey(t => t.Id);
// One to Many with client profile
entityBuilder.HasOne(c => c.ClientProfile).WithMany(p => p.ClientDocuments).HasForeignKey(x => x.ClientProfileId).IsRequired();
// One to Many with document
entityBuilder.HasOne(c => c.Document).WithMany(p => p.ClientDocuments).HasForeignKey(x => x.DocumentId).IsRequired();
}
and a ClientDocumentViewModel as follows:
public class ClientDocumentViewModel
{
public int Id { get; set; }
public int CreatedBy { get; set; }
public DateTime AddedDate { get; set; }
[HiddenInput]
public int ClientProfileId { get; set; }
public string ClientProfileName { get; set; }
public int SecondaryClientProfileId { get; set; }
[HiddenInput]
public string SecondaryClientProfileName { get; set; }
public int DocumentOwnerId { get; set; }
public int DocumentId { get; set; }
public DocumentViewModel Document { get; set; }
}
When i pass the ClientDocumentViewModel into the mapper and map the view model to the data model using:
var entity = _mapper.Map<ClientDocumentViewModel, ClientDocument>(model);
The properties from the ViewModel are all correctly getting mapped to the data model, however the mapper is also initializing an instance of ClientProfile which is stopping the insert using entity framework.
I have other data models and view models which use the same mapping pattern. When I debug them, the ClientProfile property isn't being initialized and the data entity is inserted successfully. I've gone through and compared the data models, entity framework maps, the foreign keys on the db, and the mapping profiles, and they all seem the same.
Does anyone have any ideas why this is occurring?