Automapper creating new instance rather than map properties - c#

This is a long one.
So, I have a model and a viewmodel that I'm updating from an AJAX request. Web API controller receives the viewmodel, which I then update the existing model using AutoMapper like below:
private User updateUser(UserViewModel entityVm)
{
User existingEntity = db.Users.Find(entityVm.Id);
db.Entry(existingEntity).Collection(x => x.UserPreferences).Load();
Mapper.Map<UserViewModel, User>(entityVm, existingEntity);
db.Entry(existingEntity).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch
{
throw new DbUpdateException();
}
return existingEntity;
}
I have automapper configured like so for the User -> UserViewModel (and back) mapping.
Mapper.CreateMap<User, UserViewModel>().ReverseMap();
(Note that explicitly setting the opposite map and omitting the ReverseMap exhibits the same behavior)
I'm having an issue with a member of the Model/ViewModel that is an ICollection of a different object:
[DataContract]
public class UserViewModel
{
...
[DataMember]
public virtual ICollection<UserPreferenceViewModel> UserPreferences { get; set; }
}
The corresponding model is like such:
public class User
{
...
public virtual ICollection<UserPreference> UserPreferences { get; set; }
}
The Problem:
Every property of the User and UserViewModel classes maps correctly, except for the ICollections of UserPreferences/UserPreferenceViewModels shown above. When these collections map from the ViewModel to the Model, rather than map properties, a new instance of a UserPreference object is created from the ViewModel, rather than update the existing object with the ViewModel properties.
Model:
public class UserPreference
{
[Key]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
[ForeignKey("CreatedBy")]
public int? CreatedBy_Id { get; set; }
public User CreatedBy { get; set; }
[ForeignKey("User")]
public int User_Id { get; set; }
public User User { get; set; }
[MaxLength(50)]
public string Key { get; set; }
public string Value { get; set; }
}
And the corresponding ViewModel
public class UserPreferenceViewModel
{
[DataMember]
public int Id { get; set; }
[DataMember]
[MaxLength(50)]
public string Key { get; set; }
[DataMember]
public string Value { get; set; }
}
And automapper configuration:
Mapper.CreateMap<UserPreference, UserPreferenceViewModel>().ReverseMap();
//also tried explicitly stating map with ignore attributes like so(to no avail):
Mapper.CreateMap<UserPreferenceViewModel, UserPreference>().ForMember(dest => dest.DateCreated, opts => opts.Ignore());
When mapping a UserViewModel entity to a User, the ICollection of UserPreferenceViewModels is also mapped the User's ICollection of UserPreferences, as it should.
However, when this occurs, the individual UserPreference object's properties such as "DateCreated", "CreatedBy_Id", and "User_Id" get nulled as if a new object is created rather than the individual properties being copied.
This is further shown as evidence as when mapping a UserViewModel that has only 1 UserPreference object in the collection, when inspecting the DbContext, there are two local UserPreference objects after the map statement. One that appears to be a new object created from the ViewModel, and one that is the original from the existing model.
How can I make automapper update an existing Model's collection;s members, rather than instantiate new members from the ViewModel's collection? What am I doing wrong here?
Screenshots to demonstrate before/after Mapper.Map()

This is a limitation of AutoMapper as far as I'm aware. It's helpful to keep in mind that while the library is popularly used to map to/from view models and entities, it's a generic library for mapping any class to any other class, and as such, doesn't take into account all the eccentricities of an ORM like Entity Framework.
So, here's the explanation of what's happening. When you map a collection to another collection with AutoMapper, you are literally mapping the collection, not the values from the items in that collection to items in a similar collection. In retrospect, this makes sense because AutoMapper has no reliable and independent way to ascertain how it should line up one individual item in a collection to another: by id? which property is the id? maybe the names should match?
So, what's happening is that the original collection on your entity is entirely replaced with a brand new collection composed of brand new item instances. In many situations, this wouldn't be a problem, but when you combine that with the change tracking in Entity Framework, you've now signaled that the entire original collection should be removed and replaced with a brand new set of entities. Obviously, that's not what you want.
So, how to solve this? Well, unfortunately, it's a bit of a pain. The first step is to tell AutoMapper to ignore the collection completely when mapping:
Mapper.CreateMap<User, UserViewModel>();
Mapper.CreateMap<UserViewModel, User>()
.ForMember(dest => dest.UserPreferences, opts => opts.Ignore());
Notice that I broke this up into two maps. You don't need to ignore the collection when mapping to your view model. That won't cause any problems because EF isn't tracking that. It only matters when you're mapping back to your entity class.
But, now you're not mapping that collection at all, so how do you get the values back on to the items? Unfortunately, it's a manual process:
foreach (var pref in model.UserPreferences)
{
var existingPref = user.UserPreferences.SingleOrDefault(m => m.Id == pref.Id);
if (existingPref == null) // new item
{
user.UserPreferences.Add(Mapper.Map<UserPreference>(pref));
}
else // existing item
{
Mapper.Map(pref, existingPref);
}
}

In the meantime there exists an AutoMapper Extension for that particular problem:
cfg.AddCollectionMappers();
cfg.CreateMap<S, D>().EqualityComparison((s, d) => s.ID == d.ID);
With AutoMapper.EF6/EFCore you can also auto generate all equality comparisons. Plaese see AutoMapper.Collection AutoMapper.EF6 or AutoMapper.Collection.EFCore

According to the AutoMapper source file that handles all ICollection (among other things) and the ICollection Mapper:
The collection is cleared by a call to Clear() then added again, so as far as I can see there is no way that AutoMapper will be able to automagically do the mapping this time.
I would implement some logic to loop over the collections and AutoMapper.Map the ones that are the same

Related

Best way to project ViewModel back into Model

Consider having a ViewModel:
public class ViewModel
{
public int id { get; set; }
public int a { get; set; }
public int b { get; set; }
}
and an original Model like this:
public class Model
{
public int id { get; set; }
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public virtual Object d { get; set; }
}
Each time I get the view model I have to put all ViewModel properties one by one into Model. Something like:
var model = Db.Models.Find(viewModel.Id);
model.a = viewModel.a;
model.b = viewModel.b;
Db.SaveChanges();
Which always cause lots of problems. I even sometimes forget to mention some properties and then disaster happens!
I was looking for something like:
Mapper.Map(model, viewModel);
BTW: I use AutoMapper only to convert Model to ViewModel but vice-versa I always face errors.
Overall that might be not the answer, that you are looking for, but here's a quote from AutoMapper author:
I can’t for the life of me understand why I’d want to dump a DTO
straight back in to a model object.
I believe best way to map from ViewModel to Entity is not to use AutoMapper for this. AutoMapper is a great tool to use for mapping objects without using any other classes other than static. Otherwise, code gets messier and messier with each added service, and at some point you won't be able to track what caused your field update, collection update, etc.
Specific issues often faced:
Need for non-static classes to do mapping for your entities
You might need to use DbContext to load and reference entities, you might also need other classes - some tool that does image upload to your file storage, some non-static class that does hashing/salt for password, etc etc... You either have to pass it somehow to automapper, inject or create inside AutoMapper profile, and both practices are pretty troublemaking.
Possible need for multiple mappings over same ViewModel(Dto) -> Entity Pair
You might need different mappings for same viewmodel-entity pair, based on if this entity is an aggregate, or not + based on if you need to reference this entity or reference and update. Overall this is solvable, but causes a lot of not-needed noise in code and is even harder to maintain.
Really dirty code that's hard to maintain.
This one is about automatic mapping for primitives (strings, integers, etc) and manual mapping references, transformed values, etc. Code will look really weird for automapper, you would have to define maps for properties (or not, if you prefer implicit automapper mapping - which is also destructive when paired with ORM) AND use AfterMap, BeforeMap, Conventions, ConstructUsing, etc.. for mapping other properties, which complicates stuff even more.
Complex mappings
When you have to do complex mappings, like mapping from 2+ source classes to 1 destination class, you will have to overcomplicate things even more, probably calling code like:
var target = new Target();
Mapper.Map(source1, target);
Mapper.Map(source2, target);
//etc..
That code causes errors, because you cannot map source1 and source2 together, and mapping might depend on order of mapping source classes to target. And I'm not talking if you forget to do 1 mapping or if your maps have conflicting mappings over 1 property, overwriting each other.
These issues might seem small, but on several projects where I faced usage of automapping library for mapping ViewModel/Dto to Entity, it caused much more pain than if it was never used.
Here are some links for you:
Jimmy Bogard, author of AutoMapper about 2-way mapping for your entities
A small article with comments about problems faced when mapping ViewModel->Entity with code examples
Similar question in SO: Best Practices For Mapping DTO to Domain Object?
For this purpose we have written a simple mapper. It maps by name and ignores virtual properties (so it works with entity framework). If you want to ignore certain properties add a PropertyCopyIgnoreAttribute.
Usage:
PropertyCopy.Copy<ViewModel, Model>(vm, dbmodel);
PropertyCopy.Copy<Model, ViewModel>(dbmodel, vm);
Code:
public static class PropertyCopy
{
public static void Copy<TDest, TSource>(TDest destination, TSource source)
where TSource : class
where TDest : class
{
var destProperties = destination.GetType().GetProperties()
.Where(x => !x.CustomAttributes.Any(y => y.AttributeType.Name == PropertyCopyIgnoreAttribute.Name) && x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
var sourceProperties = source.GetType().GetProperties()
.Where(x => !x.CustomAttributes.Any(y => y.AttributeType.Name == PropertyCopyIgnoreAttribute.Name) && x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
var copyProperties = sourceProperties.Join(destProperties, x => x.Name, y => y.Name, (x, y) => x);
foreach (var sourceProperty in copyProperties)
{
var prop = destProperties.FirstOrDefault(x => x.Name == sourceProperty.Name);
prop.SetValue(destination, sourceProperty.GetValue(source));
}
}
}
I want to address a specific point in your question, regarding "forgetting some properties and disaster happens". The reason this happens is that you do not have a constructor on your model, you just have setters that can be set (or not) from anywhere. This is not a good approach for defensive coding.
I use constructors on all my Models like so:
public User(Person person, string email, string username, string password, bool isActive)
{
Person = person;
Email = email;
Username = username;
Password = password;
IsActive = isActive;
}
public Person Person { get; }
public string Email { get; }
public string Username { get; }
public string Password { get; }
public bool IsActive { get; }
As you can see I have no setters, so object construction must be done via constructor. If you try to create an object without all the required parameters the compiler will complain.
With this approach it becomes clear, that tools like AutoMapper don't make sense when going from ViewModel to Model, as Model construction using this pattern is no longer about simple mapping, its about constructing your object.
Also as your Models become more sophisticated you will find that they differ significantly from your ViewModels. ViewModels tend to be flat with simple properties like string, int, bool etc. Models on the other hand often include custom objects. You will notice in my example there is a Person object, but UserViewModel would use primitives instead like so:
public class UserViewModel
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool IsActive { get; set;}
}
So mapping from primitives to complex objects limits AutoMapper's usefulness.
My approach is always manual construction for the ViewModels to Model direction. In the other direction, Models to ViewModels, I often use a hybrid approach, I would manually map Person to FirstName, LastName, I'd but use a mapper for simple properties.
Edit: Based on the discussion below, AutoMapper is better at unflattering than I believed. Though I will refrain from recommending it one way or the other, if you do use it take advantage of features like Construction and Configuration Validation to help prevent silent failures.
Use Newtonsoft.Json to serialize viewmodel first and deserialize it to model.
First we need to Serialize the viewmodel:
var viewmodel = JsonConvert.SerializeObject(companyInfoViewModel);
Then Deserialize it to model:
var model = JsonConvert.DeserializeObject<CompanyInfo>(viewmodel);
Hence, all the data is passed from viewmodel to model easily.
One Line Code:
var company = JsonConvert.DeserializeObject<CompanyInfo>(JsonConvert.SerializeObject(companyInfoViewModel));

Using AutoMapper when having a LINQ statement with multiple .Include

So I am new to using AutoMapper and have been able to get basic mapping of items no problem with using LINQ statements that do not use the .Include("blah"), however when I have a statement for example like this;
var courses = dc.Courses.Include("Students")
.Include("CourseTimes")
.OrderBy(n=>n.CourseSemester.courseStart);
AutoMapper doesnt seem to pull any of the information from ("Students") or ("CourseTimes"). My objects are posted below and to give a quick breakdown, Courses contain a List of Students(I need Students so I can count the number of people in each course), Courses also contain a List of CourseTimes(so I can display the times of each class for the given course). Here is my ViewModel that I am using.
public class UserIndexCourseList
{
[Key]
public int courseId { get; set; }
public string courseCode { get; set; }
public string courseName { get; set; }
// this simply stored a count when I did Students.Count without using AutoMapper
public int size { get; set; }
public string room { get; set; }
public List<CourseTime> courseTimeSlot { get; set; }
}
Here are some of the AutoMapper statements I tried to used but had no luck with it working.
//to the viewmodel
Mapper.CreateMap<Models.Course, ViewModels.UserIndexCourseList>();
Mapper.CreateMap<Models.CourseTime, ViewModels.UserIndexCourseList>();
Mapper.CreateMap<Models.Student, ViewModels.UserIndexCourseList>();
//from the viewmodel
Mapper.CreateMap<ViewModels.UserIndexCourseList, Models.Course>();
Mapper.CreateMap<ViewModels.UserIndexCourseList, Models.CourseTime>();
Mapper.CreateMap<ViewModels.UserIndexCourseList, Models.Student>();
So essentially how can I create a Map which will also pull all of that information so I can use it with my ViewModel that was posted above ? I have tried numerous options but no luck.
I apologize for a similar post I made ahead of time but I don't think I explained myself well enough the first time. Thanks again!
By convention automapper maps properties with same names, so in your case you can do this:
public class UserIndexCourseList
{
...
//rename field so it has same name as reference
public List<CourseTime> CourseTimes{ get; set; }
}
or you can rename reference in EF so it's name is courseTimeslot.
Another solution if you don't want to rename your property is to add options to map, for example:
Mapper.CreateMap<Models.Course, ViewModels.UserIndexCourseList>()
.ForMember(d => d.courseTimeSlot,
opt => opt.MapFrom(src => src.CourseTime));
Edit: also they have great documentation, your case is described here: https://github.com/AutoMapper/AutoMapper/wiki/Projection
"Because the names of the destination properties do not exactly match up to the source property (CalendarEvent.Date would need to be CalendarEventForm.EventDate), we need to specify custom member mappings in our type map configuration..."

How to only get one level deep with EntityFramework 5 on navigation properties?

Right now I have proxy creation disabled:
context.Configuration.ProxyCreationEnabled = false;
I have a data model like so (removed non-relevant fields):
public partial class Video
{
public int VideoID { get; set; }
public string Title { get; set; }
public int UserID { get; set; }
public virtual User User { get; set; }
}
public partial class User
{
public User()
{
this.Videos = new HashSet<Video>();
}
public int UserID { get; set; }
public string Username { get; set; }
public virtual ICollection<Video> Videos { get; set; }
}
I am using Unit of Work and Repository patterns to load my data like so,
Get all video's, including the user object:
var videos = videoService
.Include(v => v.User)
.Get()
I am using automapper to map from data model to domain model (hence the UI namespace in the screenshot below). When I inspect the video enumeration I get back, and look at the first item in the enumeration, I go to check the user object:
What I expect here is the VideoModel to be filled with data(ok), with only it's single UserModel entity to be filled with data(ok), and all collections in the UserModel to be empty(this is broke). As you can see in the second red box above, the Videos collection is populated with 6 videos. And on those video's, the user's are filled in. So this basically creates a very large object graph.
1) Can I make it so when using an include that it ONLY goes 1 level deep (IE doesn't fill in Video.User.Videos)?
2) Why doesn't ProxyCreationEnabled = false take care of this? Am I expecting too much?
p.s. I want to avoid creating a customer mapper for this with automapper.
p.p.s. I am doing db first, not model first
By default, EntityFramework uses lazy loading for virtual properties (such as User and Videos in your example). If you want these properties to be filled prior to them actually being accessed, you can use Include() or, to go another level deep, an Include() with a nested Select().
This default behavior, however, relies on the creation of a proxy class, which you have apparently turned off.
Not knowing all the things you're trying to do, this may not work, but it seems like you would get the behavior you wanted by simply removing ProxyCreationEnabled = false and using Include() as you have.
Also, viewing properties in the debugger may be misleading because you are in fact accessing the property when you try to view it in the debugger (which could cause the lazy loaded entity or collection to be filled right then, making you think it had been eagerly loaded).

How do I mimic the functionality of IQueryable<T>.Include(Expression<Func<T,TProperty>> path) in my custom collection?

First, a little background. I'm developing a REST API using ASP.NET Web API and Entity Framework 5 however the requirements of the system are such that several layers of logic sit between my ApiControllers and my DbContext. These layers of logic involve detaching my entities from the DbContext, applying sets of hypothetical changes to the entities in memory (a process I'm calling materialization of a change set) then allowing users to inspect the new state of the system should these changes get applied. The new state of the entities is not saved to the database immediately. Instead, the materialization is held in memory on the web server and users can inspect either the current data or one of the many materialization of a variety of change sets.
Now for my problem.
public interface IIdentifiable
{
long Id { get; set; }
}
public class Foo : IIdentifiable
{
public long Id { get; set; }
public string Name { get; set; }
public List<Bar> Bars { get; set; } // Navigation Property
}
public class Bar : IIdentifiable
{
public long Id { get; set; }
public string Name { get; set; }
public long FooId { get; set; } // Foreign Key Property
public Foo Foo { get; set; } // Navigation Property
}
public class Materialization
{
IEnumerable<Foo> Foos { get; set; }
IEnumerable<Bar> Bars { get; set; }
}
public interface IRepository<TItem> : IQueryable<TItem>, ICollection<TItem>, IDisposable
where TItem : class, IIdentifiable
{
IRepository<TItem> Include<TProperty>(Expression<Func<TItem, TProperty>> path);
// Other methods
}
public class MateriailizationRepository<TItem> : IRepository<TItem>
where TItem : class, IIdentifiable
{
private Materialization _materialization;
public MateriailizationRepository(Materialization materialization)
{
_materialization = materialization;
}
public IRepository<TItem> Include<TProperty>(Expression<Func<TItem, TProperty>> path)
{
// Populate navigation property indicated by "path"
}
// Other methods
}
Each Bar has a foreign key property indicating the Foo it belongs to but the Bar.Foo and Foo.Bars navigation properties are not populated as this would complicate with the materialization process. Hence, after materialization has completed, Materialization.Foos and Materialization.Bars contain collections of objects that refer to each other by foreign key properties but not by navigation properties (i.e. the values of all navigation properties are null or empty List<T>s). I want to be able to do something like the following in my ApiController.
public IQueryable<Foo> Get (bool includeBars = false)
{
Materialization materialization;
// Materialize
using (IRepository<Foo> repository = new MateriailizationRepository<Foo>(materialization))
{
IRepository<Foo> query = repository;
if (includeBars)
query = query.Include(f => f.Bars);
return query;
}
}
MateriailizationRepository<Foo>'s primary responsibility is to fetch materialized Foo objects but since it has a reference to the entire Materialization I would like to be able to include materialized Bar objects from Materiailization.Bars on demand.
How would I go about implementing MateriailizationRepository.Include() to mimic the IQueryable.Include() extension method?
Here are a couple of options:
Look at using another context to implement your MaterializationRepositories and have it backed by an in memory database such as Effort, if that's still working nowadays.
Re-implement the 'Include' functionality yourself on the Materialization. The Expression can be broken down to find the type of the navigation property. Using naming conventions you can work out what foreign key property you need to interrogate to get the correct identifier. To find the target repository you could use reflection over the Materialization looking for the public property of type IEnumerable of the type of the navigation property. As long as you knew the name of the primary key of the target entity (by convention, say) you could then use the foreign key value to find it.
If you have a small number of entity types you'd probably be better off having some kind of switch statement and do some of it manually rather than via reflection.
Apologies that this isn't a fully worked through implementation, but I hope it leads in the right direction.

Automapper Composite DTO to ViewModel conversion

In some cases there is a need to return composite DTOs from our repository, where the DTO just has a few properties that are Model properties and the function of the DTO is just to be a simple composite object (returning a Queryable is not enough because there is more information than T)
For example:
Model:
public class Job
{
int Id { get; set; }
//more properties
}
public class JobApplication
{
int Id { get; set; }
//more properties
}
Repository:
IQueryable<JobAndUserApplication> GetJobAndMatchingUserApplication(int userId):
public class JobAndUserApplication
{
public Job Job { get; set; }
public JobApplication JobApplication { get; set; }
}
Now - Id like to simply do (Project and To are Automapper functionality):
//this allows one efficient query to bring in the subproperties of the composite DTO
var jobVmList = jobRepository.GetAllJobsAndMatchingJobApplicationByUser(userId)
.Project()
.To<JobVM>()
.ToList();
So I need a mapping kind of like this:
Mapper.CreateMap<JobAndUserApplication, JobVM>()
.ForMember(jvm => jvm, opt => opt.ResolveUsing(src => src.Job));
//many other .ForMembers that are not relevant right now
I am attempting to map the Job property of the DTO directly on to the JobVM (which shares many of the same properties).
My mapping throws the following exception:
Custom configuration for members is only supported for top-level individual members on a type.
What am I doing wrong and how can I accomplish the mapping form the Job property of the DTO on the the JobVM itself?
Thanks
Automapper is telling you that you can only define custom actions on a member (property) of a class, not on the class itself. What you need to do is first create a Job to JobVM map:
Mapper.CreateMap<Job, JobVM>()
and
Mapper.CreateMap<JobAndUserApplication, JobVM>()
being sure to ignore and set any duplicate properties across the two types. Then run automapper twice, first from the child object:
var jobVM = Mapper.Map<Job, JobVM>(jobAndUserApplication.job);
then from the parent object
Mapper.Map<JobAndUserApplication, JobVM>(jobAndUserApplication, jobVM );
Or the other way around, depending on how your properties are laid out.
Quick side note: I have a feeling you might be mixing concerns, and my code smell alarm is going off. I'd take a second look at either your viewmodel or domain model, as this is not a typical issue I see come up. (just my $0.02 :-)

Categories

Resources