0

We're using AutoMapper to do our dababase<=>viewmodel conversions.

In our database, we have a record that contains a customerid. Our viewmodel does not.

When we map from the database to the viewmodel, it's easy enough to ignore the customerid. But when we map from the viewmodel to the database, how can we set the customerid?

We know the value we want it to be set to, at the time we're doing the mapping, but how do we get it into the map configuration?

public class DbUser
{
    public string customerid { get; set; }
    public string userid { get; set; }
    public string userinfo { get; set; }
}

public class UserModel
{
    public string userid { get; set; }
    public string userinfo { get; set; }
}

// mapping DbUser to UserModel is trivial
Mapper.CreatedMap<DbUser, UserModel>();

// mapping UserModel to DbUser, how do we set customerid?
Mapper.CreatedMap<UserModel, DbUser>()
    .ForMember(u => u.customerid, opt => opt.Ignore();

// One way is simple
var dbUser = this.dbContext.DbUsers.FirstOrDefault();
var userModel = Mapper.Map<UserModel>(dbUser);

// The other way I don't like
var userModel = getUserModel();
var dbUser = Mapper.Map<DbUser>(userModel);
dbUser.customerid = "TheCustomerid";

Is there a way of setting the customerid within the mapping, where the value is provided at the time the mapping is done, rather than setting the value afterwards?

Jeff Dege
  • 11,190
  • 22
  • 96
  • 165
  • Why can't you write `.ForMember(d => d.customerid, opt => opt.UseValue("TheCustomerid"))` in your mapping config? Do you retrieve a `DbUser` from the database in order to take its `constomerId`? – Ivan Gritsenko Feb 08 '17 at 22:31
  • The customerid isn't fixed at compile time, it's dependent upon who the logged-in user is. – Jeff Dege Feb 09 '17 at 00:00
  • Do you use some kind of a DI container? What type of application is it? – Ivan Gritsenko Feb 09 '17 at 09:07
  • @JeffDege I wouldn't recommend to use AutoMapper to map entities from models: [The mapping to entity Problem](http://stackoverflow.com/a/40082389/6666799) – Rabban Feb 09 '17 at 09:43
  • Mapping to and from EF entities is 80-90% of the mapping we need to do. – Jeff Dege Feb 09 '17 at 15:33
  • How do you get `CustomerId` value? There is a few possibilities to handle your case and keep mapping logic in one place, e.g. custom value resolvers. – Pawel Maga Feb 13 '17 at 20:31
  • It's injected into the http request based on the user's login information. A custom value resolver should work. Put it in an answer and I'll mark it accepted. – Jeff Dege Feb 14 '17 at 17:05

0 Answers0