AutoMapper - mapping individual ints to an array - c#

I have 12 integers representing 12 months in an old database, and I need to map them to an array/list. The problem is I'm not sure how I can initialize the array in the model to size 12, in order to map it.
Here's what I'm trying to do:
Model:
public class Year
{
public int[] Months { get; set; } //How do I initialize to 12?
}
Mapping:
CreateMap<DataRow, Year>()
.ForMember(dest => dest.Months[0], opt => opt.MapFrom(src => src["Jan"]))
.ForMember(dest => dest.Months[1], opt => opt.MapFrom(src => src["Feb"]))
.ForMember(dest => dest.Months[2], opt => opt.MapFrom(src => src["Mar"]))
I've searched everywhere for pre-initialized arrays in models, but couldn't find anything on the syntax.

Very simple:
public class Year
{
public int[] Months { get; } = new int[12];
}
I also suggest to remove setter, make it as read only property - does not change ability to set individual items in array itself.

Related

Dynamically passing properties in Select for projection in Entity Framework

Is there a way to pass the properties I want to retrieve from the DB in a Select dynamically, I don't know the properties I need beforehand and I don't want to write the conditions in my repository.
I don't want to retrieve all the fields at once, just the ones I need based on some conditions.
For example:
public class Student
{
public string Property1 {get; set;}
public string Property2 {get; set;}
//other properties here
[NotMapped]
public string Selected
{
if(condition)
return Property1;
else
return Property2;
}
}
and in the service layer I have
query.Select(s => new StudentViewModel
{
Value = s.Selected; //this one will get the property we want based on a condition
//other stuff here
//OtherValue = s.OtherProperty
}
).FirstOrDefault();
Selector
An easy but ugly way is to use a Selector:
query.Select(Selector()).FirstOrDefault();
And the Selector can look like this:
private static Expression<Func<Student, StudentViewModel>> Selector()
{
if (Condition())
return x => new StudentViewModel
{
Name = x.Property1,
OtherName = x.OtherName
};
return x => new StudentViewModel
{
Name = x.Property2,
OtherName = x.OtherName
};
}
As you can see the obviously downside here is that you need to copy/paste all other selected properties. That is why its ugly.
AutoMapper
Configs
You can use AutoMapper with different configurations. First you need to define a standard mapping for all properties that don't need to be dynamic.
public static void AddStandardStudentMap(this IMappingExpression<Student, StudentViewModel> map)
{
map.ForMember(dest => dest.OtherName, opt => opt.MapFrom(src => src.OtherProperty))
.ForMember(dest => dest.OtherName2, opt => opt.MapFrom(src => src.OtherProperty2));
// you can concat .ForMember() for each property you need.
}
Next, you need to define the different configs and add the AddStandardStudentMap method to each invidual mapping.
var config1 = new MapperConfiguration(cfg =>
cfg.CreateMap<Student, StudentViewModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Property1))
.AddStandardStudentMap()
);
var config2 = new MapperConfiguration(cfg =>
cfg.CreateMap<Student, StudentViewModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Property2))
.AddStandardStudentMap()
);
After this, just use your conditions to decide which config do you need
IConfigurationProvider provider;
if(Condition())
provider = config1;
else
provider = config2;
And then instead of .Select() use:
query.ProjectTo<StudentViewModel>(provider).FirstOrDefault();
As we can see this solution is still ugly and has a lot of overhead but its needed in some cases, thats why i stated it here.
Expression
This is a bit similar to the Configs but brings you more flexibility and less writing effort.
First create a config but this time with a Selector
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<Student, StudentViewModel>()
.ForMember(dest => dest.OtherName, opt => opt.MapFrom(src => src.OtherName))
.ForMember(dest => dest.OtherName2, opt => opt.MapFrom(src => src.OtherName2))
// and so on. Map all your properties that are not dynamically.
// and then the Selector
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => Selector()))
);
The Selector method can look like this:
private static Expression<Func<Student, StudentViewModel>> Selector()
{
if(Condition())
return src => src.Property1;
else
return src => src.Property2;
}
And then just use it like the configs solution but without selecting a particular config:
query.ProjectTo<StudentViewModel>(config).FirstOrDefault();
Conclusion
I know this is a lot input and there are even more possibilities to achieve the behaviour that you want, with or without AutoMapper. But i would suggest you (grounded on the information you gave us) to use AutoMapper with Expressions. It should give the flexibility you need and is extensible for further requirements.

How to correctly configure `int?` to `int` projections using AutoMapper?

I'm having some trouble getting this to work correctly. I have two classes:
public class TestClassA
{
public int? NullableIntProperty { get; set; }
}
public class TestClassB
{
public int NotNullableIntProperty { get; set; }
}
I then set up the following mappings:
cfg.CreateMap<TestClassA, TestClassB>()
.ForMember(dest => dest.NotNullableIntProperty,
opt => opt.MapFrom(src => src.NullableIntProperty));
cfg.CreateMap<TestClassA, TestClassA>()
.ForMember(dest => dest.NullableIntProperty,
opt => opt.MapFrom(src => src.NullableIntProperty));
cfg.CreateMap<TestClassB, TestClassA>()
.ForMember(dest => dest.NullableIntProperty,
opt => opt.MapFrom(src => src.NotNullableIntProperty));
cfg.CreateMap<TestClassB, TestClassB>()
.ForMember(dest => dest.NotNullableIntProperty,
opt => opt.MapFrom(src => src.NotNullableIntProperty));
I now have four mappings set up, and will test the following scenarios:
int? => int
int => int?
int => int
int? => int?
In a test class, I then use the mappings like this:
var testQueryableDest = testQueryableSrc.ProjectTo<...>(_mapper.ConfigurationProvider);
The only projection I would expect not to work at this stage would be TestClassA => TestClassB, since I can see how AutoMapper may not know what to do with the int? in cases where the value is null. Sure enough, that's exactly the case. So I set up a mapping for int? => int like so:
cfg.CreateMap<int?, int>()
.ProjectUsing(src => src ?? default(int));
This is where things become strange. As soon as I add this mapping, the mapping from TestClassB => TestClassB fails to even create. It gives this error message:
Expression of type 'System.Int32' cannot be used for assignment to type 'System.Nullable`1[System.Int32]'
I find this message incredibly strange as TestClassB does not have an int? on it at all. So what's going on here? I feel like I must be misunderstanding something about how AutoMapper needs these projections to be handled. I realise the various bits of code may be tricky to piece together so here's the entire test class for reference:
[TestClass]
public class BasicTests
{
private readonly IMapper _mapper;
public BasicTests()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<int?, int>()
.ProjectUsing(src => src ?? default(int));
cfg.CreateMap<TestClassA, TestClassB>()
.ForMember(dest => dest.IntProperty, opt => opt.MapFrom(src => src.NullableIntProperty));
cfg.CreateMap<TestClassA, TestClassA>()
.ForMember(dest => dest.NullableIntProperty, opt => opt.MapFrom(src => src.NullableIntProperty));
cfg.CreateMap<TestClassB, TestClassA>()
.ForMember(dest => dest.NullableIntProperty, opt => opt.MapFrom(src => src.IntProperty));
cfg.CreateMap<TestClassB, TestClassB>()
.ForMember(dest => dest.IntProperty, opt => opt.MapFrom(src => src.IntProperty));
});
_mapper = new Mapper(config);
}
[TestMethod]
public void CanMapNullableIntToInt()
{
var testQueryableSource = new List<TestClassA>
{
new TestClassA
{
NullableIntProperty = null
}
}.AsQueryable();
var testQueryableDestination = testQueryableSource.ProjectTo<TestClassB>(_mapper.ConfigurationProvider);
}
[TestMethod]
public void CanMapNullableIntToNullableInt()
{
var testQueryableSource = new List<TestClassA>
{
new TestClassA
{
NullableIntProperty = null
}
}.AsQueryable();
var testQueryableDestination = testQueryableSource.ProjectTo<TestClassA>(_mapper.ConfigurationProvider);
}
[TestMethod]
public void CanMapIntToNullableInt()
{
var testQueryableSource = new List<TestClassB>
{
new TestClassB
{
IntProperty = 0
}
}.AsQueryable();
var testQueryableDestination = testQueryableSource.ProjectTo<TestClassA>(_mapper.ConfigurationProvider);
}
[TestMethod]
public void CanMapIntToInt()
{
var testQueryableSource = new List<TestClassB>
{
new TestClassB
{
IntProperty = 0
}
}.AsQueryable();
var testQueryableDestination = testQueryableSource.ProjectTo<TestClassB>(_mapper.ConfigurationProvider);
}
}
I’ve found the shortest way to reproduce this situation is the following:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<int?, int>().ProjectUsing(x => x ?? default(int));
cfg.CreateMap<TestClassA, TestClassA>()
.ForMember(a => a.NullableIntPropety, o => o.MapFrom(a => a.NullableIntProperty));
}
It seems to me that AutoMapper is attempting to use the int? => int mapper here although a more obvious identity-based mapping would be to use here.
Since every int is also a valid int?, AutoMapper attempts to use the int? => int mapper here and assign the result to the int? member. But it seems that under the hood something does not correctly work when resolving just that assignment, hence that exception.
What seems to fix it is to add another mapping, an identity mapping for int? => int?:
cfg.CreateMap<int?, int?>().ProjectUsing(x => x);
Then, this mapping is being used instead and no exception occurs (and the mapping also properly works—with all of your examples).
This problem seems to exist on the current AutoMapper 5.1.x release (current is 5.1.1). The good news is, that it has already been fixed. If you try the current 5.2 alpha from the myget feed, then the code works fine without any issues.
Since the 5.1.1 release, the code base has seen quite a few contributions with multiple fixes on nullable mapping (e.g. this and this pull request). I assume that one of those changes has fixed this problem.
Most likely, it was pull request #1672 which just meant to remove unneeded code but apparently also fixed issue 1664 which was about AutoMapper apparently prioritizing nullable source mappings over non-nullable sources even if a non-nullable source was being mapped. And that sounds very much like this very problem you have experienced.
So, for now, you can add above workaround to map the type to itself or use an alpha release, while we wait for 5.2 to be released.

Creating a DateTime using AutoMapper

I am struggling to create a DateTime object from (year, month, day) which is being returned from the database. I am rather new to AutoMapper so a nudge in the right direction would be great.
Here is the ViewModel containing the DateTime object and the three values that need to be used to create the DateTime:
public class EnquiriesListViewModel
{
// other field elided
public sbyte flightDay;
public sbyte flightMonth;
public bool flightYear
public DateTime flightDate;
// other field elided
}
I would like AutoMapper to construct the flightDate from the other three values. I have tried various approaches, some of which didn't even compile!
Like this:
Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
.ForMember(dest => dest.flightDate, /* what goes in here? */);
Looking forward to your responses.
M
Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
.ForMember(dest => dest.flightDate, opt => opt.MapFrom(src => new DateTime(src.flightYear, src.flightMonth, src.flightDay)));
Should do it.
This solution is coming too late but its good because it applies to .NET 4.6.1
Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()
.ForMember(dest => dest.flightDate,
opt => opt.AddTransform(src => new DateTime(src.Year,
src.Month,
src.Day)));

How to map Integer to String with AutoMapper 3 and Entity Framework

I am trying to use AutoMapper 3 to project a class with an Integer property to another class with a String property.
When the query is executed then I get the following exception:
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Here are the relevant parts of the code:
public partial class Lookup
{
public int LookupId { get; set; }
public int LookupTypeId { get; set; }
public string Value { get; set; }
public int SequencialOrder { get; set; }
public virtual LookupType LookupType { get; set; }
}
public class LookupProfile : Profile
{
protected override void Configure()
{
CreateMap<Lookup, SelectListItem>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.LookupId.ToString()))
.ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value));
}
}
And the query looks like:
Provinces = _db.Lookups.Project().To<SelectListItem>().ToList()
Question:
Is there a way I could configure the LookupProfile to do the proper mapping and still work inside Linq To Entities?
Or is there another way I could make the projection work with Linq to Entities?
The solution was to use the SqlFunctions.StringConvert function.
Here is the modified profile code that made everything work:
public class LookupProfile : Profile
{
protected override void Configure()
{
CreateMap<Lookup, SelectListItem>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => SqlFunctions.StringConvert((double)src.LookupId)))
.ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value));
}
}
I'll leave this answer here in case anyone else stumbles upon the same issue I had.
One problem with the current accepted answer is that if you're on an ASP.NET MVC project using client-side validation through helpers, you'll get a validation error for the ID field (if it's a number): The field [field] must be a number. That happens because the result from SqlFunctions.StringConvert returns a string with several leading spaces, so the unobtrusive validator doesn't see it as a number.
The way I solved this issue on my own was to create a generic SelectListItem<T> class that inherits from SelectListItem, hides the original Value property and implements its own Value setter:
public class SelectListItem<T> : SelectListItem
{
public new T Value {
set {
base.Value = value.ToString();
}
// Kind of a hack that I had to add
// otherwise the code won't compile
get {
return default(T);
}
}
}
Then on the Automapper profile I would map the items like so:
public class LookupProfile : Profile
{
protected override void Configure()
{
//Use whatever datatype is appropriate: decimal, int, short, etc
CreateMap<Lookup, SelectListItem<int>>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.LookupId))
.ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value));
}
}
And finally on the Service layer, I would map the entities to the generic class and return an IEnumerable<SelectListItem>.
public IEnumerable<SelectListItem> GetList() {
return _db.Lookups.Project().To<SelectListItem<int>>().ToList();
}
This way you'll get the right value for the Value property without trailing spaces.

Can AutoMapper be "persuaded" to temporarily suspend particular mappings?

Can AutoMapper be "persuaded" to temporarily suspend particular mappings?
To illustrate what am trying to accomplish, I will use an illustration. Suppose that I have a repository, StudentRepository, that uses LINQ to interacts with database objects (tables) like Students, Courses, Activities, Clubs etc. On the application side, there are matching domain objects Student, Course, Activity, Club. The Student class contains array members of type Course, Activity, and Club like:
public class Student
{
// ... more members
public Course[] Courses { get; set; }
public Activity[] Activities { get; set; }
public Club[] Clubs { get; set; }
// ... even more members
}
AutoMapper is configured to map the database objects to the domain objects where the mappings are defined in a static constructor of StudentRepository like:
public class StudentRepository : IStudentRepository
{
static class StudentRepository
{
// ... other mappings
Mapper.CreateMap<TableStudent, Student>()
.ForMember(dest => dest.Courses, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Course>>(src.TableCourses)))
.ForMember(dest => dest.Activities, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Activity>>(src.TableActivities)))
.ForMember(dest => dest.Clubs, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Clubs>>(src.TableClubs)))
// where TableStudents, TableCourses, TableActivities, TableClubs are database entities
// ... yet more mappings
}
}
Is it possible to "persuade" AutoMapper to suspend the mappings within one function block? For example:
public Student[] GetStudents()
{
DataContext dbContext = new StudentDBContext();
var query = dbContext.Students;
// => SUSPEND CONFIGURATION MAPPINGS for Subjects, Activities and Clubs WHILE STILL making use of others
// => The idea here it to take personal charge of 'manually' setting the particular members (*for some specific reasons)
var students = Mapper.Map<Student>(query); // => Still be able to use AutoMapper to map other members
}
public Student[] OtherStudentRepositoryMethods()
{
// Other repository methods continue to make use of the mappings configured in the static constructor
}
NOTE "for some specific reasons": One reason one may want to take control away from AutoMapper would be this http://codebetter.com/davidhayden/2007/08/06/linq-to-sql-query-tuning-appears-to-break-down-in-more-advanced-scenarios/ where in the case of a 1:n associations, LINQ to SQL only supports joining-in one 1:n association per query. AutoMapper would be inefficient here - making N calls to load Courses for N students returned, N more calls to load Activities for the same N students returned, and possibly N more calls to load Clubs for the same N students returned.
Is it possible to "persuade" AutoMapper to suspend the mappings within one function block?
As I know, the best way to do it - use Ignore() like this
public class StudentRepository : IStudentRepository
{
static class StudentRepository
{
// ... other mappings
Mapper.CreateMap<TableStudent, Student>()
.ForMember(dest => dest.Courses, opt => opt.Ignore())
.ForMember(dest => dest.Activities, opt => opt.Ignore())
.ForMember(dest => dest.Clubs, opt => opt.Ignore())
// where TableStudents, TableCourses, TableActivities, TableClubs are database entities
// ... yet more mappings
}
}
Also, as it was noticed before, I'd recommend you to use different profiles for each goal you want to achieve.Here is a example
public BaseService()
{
AutoMapperRegistry.Configure();
}
public class AutoMapperRegistry
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<ServiceProfile1>();
x.AddProfile<ServiceProfileReverseProfile1>();
});
}
}
public class ServiceProfile1 : Profile
{
protected override string ProfileName
{
get
{
return "ServiceProfile1";
}
}
protected override void Configure()
{
Mapper.CreateMap<DataContract_Sub, DTO_Sub>();
Mapper.CreateMap<DataContract, DTO>()
.ForMember(x => x.DataContract_Sub, opt => opt.MapFrom(y => y.DTO_Sub))
.BeforeMap((s, d) =>
{
// your custom logic
})
.AfterMap((s, d) =>
{
// your custom logic
});
}
}
One way of achieving this would be to create separate mapping engine instances for each scenario, that way you could configure different maps, as suggested in this answer from Jimmy Bogard on wanting to map a single type in different ways.
hmm... Thanks guys for the feedback. I took time to consider all answers and suggestions. None particularly renders exactly well though they provided a lot of food for thought. I thought I should inject something I tried. (Disclaimer: My opinion is that its a dirty approach - many things could go wrong - and Murphy's laws continue to hold). You could leverage the Ignore functionality in the particular instance to "suspend" the mapping. Typically, in a try and catch block as follows:
public Student[] GetStudents()
{
try
{ // Suspend/Ignore the mappings
// => SUSPEND CONFIGURATION MAPPINGS for Subjects, Activities and Clubs
Mapper.CreateMap<TableStudent, Student>()
.ForMember(dest => dest.Courses, opt => opt.Ignore())
.ForMember(dest => dest.Activities, opt => opt.Ignore())
.ForMember(dest => dest.Clubs, opt => opt.Ignore())
DataContext dbContext = new StudentDBContext();
var query = dbContext.Students;
// other logic ...
var students = Mapper.Map<Student>(query); // => Still be able to use AutoMapper to map other members
// set the properties you needed to do manually
}
finally // Restore back the mappings
{
Mapper.CreateMap<TableStudent, Student>()
.ForMember(dest => dest.Courses, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Course>>(src.TableCourses)))
.ForMember(dest => dest.Activities, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Activity>>(src.TableActivities)))
.ForMember(dest => dest.Clubs, opt => opt.MapFrom(src => Mapper.Map<IEnumerable<Clubs>>(src.TableClubs)))
}
}
Like I mentioned, its perhaps dirty. Not the kind of code I would be happy wriing - especially since I don't know what kind of exceptional situations can arise if CreateMap() fails within the finally block, but on a legacy application where you couldn't overhaul the approach - to possibly use different profiles like suggested by #AndriyZakharko above, you could use it to get control back temporarily. I tried it out personally.

Categories

Resources