AutoMapperConfigurationException: AutoMapper throwing exception without showing property name - asp.net-web-api

I am creating POC using Asp.Net Web API. For mapping one object type to another i am using AutoMapper(v5.1.1). Here are the types which is being used for mapping:
//Entity
public class Goal : IVersionedEntity
{
public virtual int GoalId { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual DateTime StartDate { get; set; }
public virtual DateTime EndDate { get; set; }
public virtual string Reward { get; set; }
public virtual DateTime? DisabledDate { get; set; }
public virtual byte[] Version { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Schedule> Schedules { get; set; }
}
//Model
public class Goal
{
private List<Link> _links;
public int GoalId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
//public Status Status { get; set; }
public string Reward { get; set; }
public DateTime? DisabledDate { get; set; }
public User User { get; set; }
public ICollection<Schedule> Schedules { get; set; }
public List<Link> Links
{
get { return _links ?? (_links = new List<Link>()); }
set { _links = value; }
}
public void AddLink(Link link)
{
_links.Add(link);
}
}
I am mapping Goal Entity to Goal model type object as following:
public async System.Threading.Tasks.Task Configure()
{
Mapper.Initialize(cfg => cfg.CreateMap<Data.Entities.Goal, Models.Goal>()
.ForMember(m => m.Links, i => i.Ignore()));
}
and here is the 'AutoMapperConfigurator' class in 'App_Start':
public void Configure(IEnumerable<IAutoMapperTypeConfigurator> autoMapperTypeConfigurations)
{
autoMapperTypeConfigurations.ToList().ForEach(m => m.Configure());
Mapper.AssertConfigurationIsValid();
}
But it is throwing following exception:
The following property on TestApp.Web.Api.Models.Goal cannot be
mapped: Add a custom mapping expression, ignore, add a custom
resolver, or modify the destination type TestApp.Web.Api.Models.Goal.
Context: Mapping from type TestApp.Data.Entities.Goal to
TestApp.Web.Api.Models.Goal Exception of type
'AutoMapper.AutoMapperConfigurationException' was thrown.
See it's not showing which property is not getting mapped.
Any help for this isssue.

After spending hours on this, my final findings are follows:
You must have all your entity models and service models mapping correct to make it work. Even if one fails, the mentioned exception will be thrown. And if your complex type mappings are not correct you will get the above error.
In my case, I was missing how to configure the Complex Type with AutoMapper.
To configure Complex Type, either add .ForMember(m => m.Property, i => i.Ignore()) to ignore the complex type mapping if not needed or .ForMember(m => m.Property, i => i.MapFrom(j => Mapper.Map<Entity,ServiceModel>(j.Property))) for nested mapping (refer: http://www.softwarerockstar.com/2011/05/complex-object-mapping-using-automapper/) or use CustomMapping if there is come specific requirement during the mapping

Related

How to handle char property properly in Hotchocolate Graphql 12.0?

I am trying to implement filtering on Resource table which has MartialStatus of char property in DDL of database.Let my show you my approach first. In my program.cs file, i have the following:
using LIS.ResourcePlanningSystem.API;
using LIS.ResourcePlanningSystem.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<RpsDbContext>(options => options.UseLazyLoadingProxies().UseNpgsql(builder.Configuration.GetConnectionString("RPSDbContext")));
builder.Services.AddGraphQLServer().
RegisterDbContext<RpsDbContext>().
AddQueryType<Query>().
AddProjections().
AddFiltering().
AddSorting().
BindRuntimeType<char, StringType>().
AddTypeConverter<char, string>(from => from.ToString()).
AddTypeConverter<string, char>(from => from.ToCharArray()[0]);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapGraphQL("/graphql");
app.Run();
Here is my a model Register.cs which has "MaritalStatus" char property.
public class Resource
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? MiddleName { get; set; }
public string? LastName { get; set; }
public string? FullName { get; set; }
public char? MaritalStatus { get; set; }
public virtual Gender? Gender { get; set; }
public virtual Education? Education { get; set; }
public int? InstitutionId { get; set; }
public string? PerStreet { get; set; }
public DateTime? OfficeJoinDt { get; set; }
public virtual Grade? Grade { get; set; }
public int? PositionId { get; set; }
public virtual Department? Department { get; set; }
public virtual ClientType? ClientType{ get; set; }
public int? ExpOut { get; set; }
public string? ResignedFlag { get; set; }
public string? Email { get; set; }
public virtual BloodGroup? BloodGroup { get; set; }
public virtual ResignedRemarks? ResignedRemark { get; set; }
public virtual Source? Source { get; set; }
}
Now, the program runs just fine until i add [UseFiltering] on the Resource table in query.cs file.
[UseFiltering]
[UseSorting]
public IQueryable<Resource>? GetResources(RpsDbContext context) => context.Resources;
The error i am getting is this:
HotChocolate.SchemaException: For more details look at the `Errors` property.
1. For more details look at the `Errors` property.
1. The type of the member MaritalStatus of the declaring type Resource is unknown
If i remove the [UseFiltering] [UseSorting], the program works fine. I think the problem is related to filtering on resource table. Filtering also work fine on all the other tables which doesn't have char property in its schema definition. Someone has opened a bug issue on github [here] . Tried to solve reading this issue but no luck. Could somebody please tell me how can i get around this problem?

Entity History is not working in aspnetboilerplate

I am using aspnetboilerplate and added below configuration in preintiliaze in module. I have also added data annotation Audited to my entity but still it is not working. My entity is inheriting from AuditedEntity as don't need deleted feature. Please help
Configuration.EntityHistory.IsEnabled = true; Configuration.EntityHistory.Selectors.Add(new NamedTypeSelector("Abp.AuditedEntities", type => typeof(AuditedEntity).IsAssignableFrom(type)));
I have taken reference from here Can't enable Entity History in ASP.NET Zero
Below is entity definition
[Audited]
public partial class QuestionResponse : AuditedEntity<long>
{
public long ApplicationId { get; set; }
public long QuestionId { get; set; }
public string Response { get; set; }
public string Remark { get; set; }
public bool IsActive { get; set; }
public Application Application { get; set; }
public AbpUsers CreatorUser { get; set; }
public AbpUsers LastModifierUser { get; set; }
public Question Question { get; set; }
}
AuditedEntity<long> is not assignable to AuditedEntity.
Add a selector based on the interface IAuditedEntity instead.
Configuration.EntityHistory.Selectors.Add(
new NamedTypeSelector("Abp.AuditedEntities", type =>
// typeof(AuditedEntity).IsAssignableFrom(type)));
typeof(IAuditedEntity).IsAssignableFrom(type)));
Reference
From aspnetboilerplate/aspnetboilerplate's AuditedEntity.cs:
public abstract class AuditedEntity : AuditedEntity<int>, IEntity
{
}
public abstract class AuditedEntity<TPrimaryKey> : CreationAuditedEntity<TPrimaryKey>, IAudited
{
...
}

Data Annotation for foreign key relationship

I have two classes
public class Project
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int ManagerID { get; set; }
public int CoordID { get; set; }
[ForeignKey("ManagerID")]
public virtual Employee Manager { get; set; }
[ForeignKey("CoordID")]
public virtual Employee Coord { get; set; }
}
public class Employee
{
[Key]
public int EmpID { get; set; }
public string Name { get; set; }
[InverseProperty("ManagerID")]
public virtual ICollection<Project> ManagerProjects { get; set; }
[InverseProperty("CoordID")]
public virtual ICollection<Project> CoordProjects { get; set; }
}
The ManagerID and CoordID map to the EmpID column of the Employee table.
I keep getting an error for Invalid Columns becauce EF is not able to map correctly. I think it is looking for wrong column.
I think InverseProperty is used to refer to the related navigation property, not the foreign key, e.g.
public class Employee
{
[Key]
public int EmpID { get; set; }
public int Name { get; set; }
[InverseProperty("Manager")]
public virtual ICollection<Project> ManagerProjects { get; set; }
[InverseProperty("Coord")]
public virtual ICollection<Project> CoordProjects { get; set; }
}
Also, is there a reason why your names are ints and not strings?
Best guess would be to use fluent API in your context via OnModelCreating. By renaming the column, EF can't figure out the original object to map so it's confused. However, Fluent API allows you to manually specify the map using something like the following:
public class MyContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Project> Projects { get; set; }
protected override OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.HasRequired(x => x.Manager)
.WithMany(x => x.ManagerProjects)
.HasForeignKey(x => x.ManagerID);
modelBuilder.Entity<Project>()
.HasRequired(x => x.Coord)
.WithMany(x => x.CoordProjects)
.HasForeignKey(x => x.CoordID);
}
}

How to Load Related Data in MVC with complex table structure

I have several classes which I will shorten for brevity. Below they are listed with the related properties/fields associated with this question.
public class AcademicYear
{
[Key]
public int AcademicYearId { get; set; }
}
public class Division
{
public Division()
{
this.CareerFields = new HashSet<CareerField>();
}
[Key]
public int DivisionId { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
// Navigation Properites
public virtual AcademicYear AcademicYear { get; set; }
public virtual ICollection<CareerField> CareerFields { get; set; }
}
public class CareerField
{
public CareerField()
{
this.Clusters = new HashSet<Cluster>();
}
[Key]
public int CareerFieldId { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
public int DivisionId { get; set; }
// Navigation Properties
public virtual AcademicYear AcademicYear { get; set; }
public virtual Division Division { get; set; }
public virtual ICollection<Cluster> Clusters { get; set; }
}
public class Cluster
{
public Cluster()
{
this.CareerFields = new HashSet<CareerField>();
}
[Key]
public int ClusterId { get; set; }
{
// Foreign Keys
public int AcademicYearId { get; set; }
// Navigation Properties
public virtual AcademicYear AcademicYear { get; set; }
public virtual ICollection<CareerField> CareerFields { get; set; }
}
}
public class Pathway
{
public Pathway()
{
this.CareerMajors = new HashSet<CareerMajor>();
}
[Key]
public int PathwayId { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
public int ClusterId { get; set; }
// Navigation Properties
public virtual AcademicYear AcademicYear { get; set; }
public virtual Cluster Cluster { get; set; }
public virtual ICollection<CareerMajor> CareerMajors { get; set; }
}
public class CareerMajor
{
public CareerMajor()
{
this.Courses = new HashSet<Course>();
}
[Key]
public int CareerMajorId { get; set; }
public string FirstYearOffered { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
public int PathwayId { get; set; }
// Navigation Properties
[HiddenInput(DisplayValue = false)]
public virtual AcademicYear AcademicYear { get; set; }
public virtual Pathway Pathway { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public Course()
{
this.CareerMajors = new HashSet<CareerMajor>();
}
[Key]
public int CourseId { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
public int? InstructorId { get; set; }
// Navigation Properties
public virtual ICollection<CareerMajor> CareerMajors { get; set; }
public virtual AcademicYear AcademicYear { get; set; }
}
I also have a ViewModel class to load all this for my controller
public class CMSIndex
{
public IEnumerable<Division> Divisions { get; set; }
public IEnumerable<CareerField> CareerFields { get; set; }
public IEnumerable<Cluster> Clusters { get; set; }
public IEnumerable<Pathway> Pathways { get; set; }
public IEnumerable<CareerMajor> CareerMajors { get; set; }
public IEnumerable<Course> Courses { get; set; }
}
I have a razor cshtml page (the auto CRUD defined Index page) where I start with the Division and I can load the related CareerFields. However, when I try to load Clusters, I get the error message
Server Error in '/' Application.
Value cannot be null.
Parameter name: source
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source
Here is my index method from the controller (note the commented out lines are what I have tried as well)
public ViewResult Index(Int32? divisionID, Int32? careerFieldID, Int32? clusterID, Int32? pathwayID, Int32? careerMajorID, Int32? courseID)
{
var viewModel = new CMSIndex();
viewModel.Divisions = db.Divisions
.Include(d => d.AcademicYear)
.Include(d => d.CareerFields)//
.Include(d => d.CareerFields.Select(cf => cf.Clusters))
//.Select(c => c.Clusters.Select(cl => cl.Pathways.Select(p => p.CareerMajors.Select(cm => cm.Courses)))))
.OrderBy(d => d.DivisionName);
if (divisionID != null)
{
ViewBag.DivisionID = divisionID.Value;
viewModel.CareerFields = viewModel.Divisions.Where(d => d.DivisionId == divisionID.Value).Single().CareerFields;
}
if (careerFieldID != null)
{
ViewBag.careerFieldID = careerFieldID.Value;
//viewModel.Clusters = viewModel.CareerFields.Where(cf => cf.CareerFieldId == careerFieldID.Value).Single().Clusters;
//viewModel.Clusters = viewModel.CareerFields.SelectMany(cf => cf.Clusters);
viewModel.Clusters = viewModel.CareerFields.Where(cf => cf.CareerFieldId == careerFieldID.Value).Single().Clusters;
}
return View(viewModel);
}
I am following the Contoso tutorial on loading related data. I seem to be able to load 1:m relationships, but I am unsure how to do this with m:m (e.g. CareerFields and Clusters).
And, I do have an initializer that has loaded data to pull and I am passing an ID (e.g. careerFieldID).
Where the exception is being thrown is on the line:
viewModel.Clusters = viewModel.CareerFields.Where(cf => cf.CareerFieldId == careerFieldID.Value).Single().Clusters;
And each commented variation.
Any help would be extremely appreciated.
Not saying that this is the issue, but have you checked the values are not null? In the line
viewModel.Clusters = viewModel.CareerFields
.Where(cf => cf.CareerFieldId == careerFieldID.Value).Single().Clusters;
is it possible that viewModel.CareerFields is null?
As some side notes:
With your null checks when you have nullables it's better to use their HasValue method e.g.
if (divisionID.HasValue)
{
...
}
The use of Single() can be a bit temperamental and can throw exceptions if no elements exist or if more than one exist. First() can be used to handle more than one (but this throws if none match), SingleOrDefault() will handle zero or one result and FirstOrDefault() will handle most things.
You can save a expression by putting your lambda in the single e.g.
viewModel.CareerFields = viewModel.Divisions
.Single(d => d.DivisionId == divisionID.Value).CareerFields;
Edit: I think the issue you are having is the same as in This Answer could you try changing your classes collections so the are initialised in the get when null. E.g for Division
public class Division
{
[Key]
public int DivisionId { get; set; }
// Foreign Keys
public int AcademicYearId { get; set; }
// Navigation Properites
public virtual AcademicYear AcademicYear { get; set; }
private ICollection<CareerField> careerFields;
public virtual ICollection<CareerField> CareerFields {
get { return careerFields ?? (careerFields = new HashSet<CareerField>()); }
set { careerFields = value; }
}
}
That's actually my preferred method anyway, this imposes it's own problem with your code as the fact that CareerFields was null means that for the given division, there are no associated CareerFields. This means that when your Single() call is hit it will throw the exception The source contains no elements as CareerFields will contain a empty hashset. This could be fixed by a change to SingleOrDefault().

Entity Framework multiple relationships between tables

I've have two tables in my project which are User and InvoiceLine.
It has been specified that an InvoiceLine can have a User known as a Checker.
My models are:
public class InvoiceLine : IEntity
{
public virtual int Id { get; set; }
public virtual int? CheckerId { get; set; }
public virtual string CreatedByUserName { get; set; }
public virtual DateTime CreatedDateTime { get; set; }
public virtual string LastModifiedByUserName { get; set; }
public virtual DateTime? LastModifiedDateTime { get; set; }
// Navigation properties
public virtual User Checker{ get; set; }
}
public class User : IEntity
{
public int Id { get; set; }
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
//Navigation properties
public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }
}
So this was fine I have a 0..1 to many relationship from User to InvoiceLine.
This meant with Linq I could get the InvoiceLines the User needs to check via:
user.InvoiceLines
However there is another requirement that an InvoiceLine also has an Auditor so I modified the InvoiceLine to:
public class InvoiceLine : IEntity
{
public virtual int Id { get; set; }
public virtual int? CheckerId { get; set; }
public virtual int? AuditorId { get; set; }
public virtual string CreatedByUserName { get; set; }
public virtual DateTime CreatedDateTime { get; set; }
public virtual string LastModifiedByUserName { get; set; }
public virtual DateTime? LastModifiedDateTime { get; set; }
// Navigation properties}
public virtual User Checker { get; set; }
public virtual User Auditor { get; set; }
}
So what I was really wanting was to go:
user.InvoiceLines
and get the Checkers and Auditors or alternatively get them seperately via:
user.CheckerInvoiceLines
user.AuditorInvoiceLines
I'm getting null back from user.InvoiceLines though which is understandable.
Could someone please point me in the right direction on how to use Linq to get the InvoiceLines from the User?
Edit Update:
My model configuration code is like:
public class VectorCheckContext : DbContext
{
...
public DbSet<InvoiceLine> InvoiceLines { get; set; }
public DbSet<User> Users { get; set; }
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
You need to use fluent mappings to configure the relationships when EF can not resolve them by conventions.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//other mappings
modelBuilder.Entity<InvoiceLine>()
.HasOptional(i => i.Checker)
.WithMany(u => u.CheckerInvoiceLines)
.HasForeignKey(i => i.CheckerId);
modelBuilder.Entity<InvoiceLine>()
.HasOptional(i => i.Auditor)
.WithMany(u => u.AuditorInvoiceLines)
.HasForeignKey(i => i.AuditorId);
}

Resources