I'm trying to use AutoMapper to take data from a class that has prefixes before property names and map it to a second class that doesn't have those prefixes. However, I don't necessarily want it to always strip out that prefix: I just want it to do it for this particular mapping.
My source class looks like this:
public class AdvancedSearchFilterDataModel
{
// ....
public string ServiceMeterNumber { get; set; }
// ....
}
My destination class looks like this:
[DataContract]
public class ServicesAdvancedSearchFilterData : AdvancedSearchFilterData
{
// ....
[DataMember]
public string MeterNumber { get; set; }
// ....
}
When I try to map values like this, it works:
Mapper.Configuration.RecognizePrefixes("Service");
Mapper.CreateMap<AdvancedSearchFilterDataModel, ServicesAdvancedSearchFilterData>();
ServicesAdvancedSearchFilterData servciesFilterData =
Mapper.Map<ServicesAdvancedSearchFilterData>(model);
But I only want "Service" to be recognized as a prefix for certain mappings, since it's also used as a normal part of property names in other mappings. I tried to handle this with a profile, but this didn't work -- no data was mapped:
Mapper.CreateProfile("ServicePrefix").RecognizePrefixes("Service");
Mapper.CreateMap<AdvancedSearchFilterDataModel, ServicesAdvancedSearchFilterData>()
.WithProfile("ServicePrefix");
ServicesAdvancedSearchFilterData servciesFilterData =
Mapper.Map<ServicesAdvancedSearchFilterData>(model);
How can I make it recognize the prefix only when I want it to, either using profiles or some other technique? (I also have other prefixes that I'm going to need it to recognize for other mappings in the same way.)
I achieved this functionality by creating following structure:
I have Person model for my view which is flattened from PersonCombined
public class PersonCombined
{
public Person Person { get; set; }
public Address DefaultAddress { get; set; }
public Contact EmailContact { get; set; }
public Contact PhoneContact { get; set; }
public Contact WebsiteContact { get; set; }
}
public class Person : IWebServiceModel
{
public int ID { get; set; }
public string PersonFirstName { get; set; }
public string PersonSurname { get; set; }
public string PersonDescription { get; set; }
public Nullable<bool> PersonIsActive { get; set; }
}
Then I have separate class for this mapping only that looks like this:
public class PersonCustomMapping : ICustomMapping
{
const string separator = " ";
private static IMappingEngine _MappingEngine;
public IMappingEngine MappingEngine
{
get
{
if (_MappingEngine == null)
{
var configuration = new ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
configuration.RecognizePrefixes("Person");
configuration.RecognizeDestinationPrefixes("Person");
configuration.CreateMap<Person, MCIACRM.Model.Combine.PersonCombined>();
configuration.CreateMap<MCIACRM.Model.Combine.PersonCombined, Person>();
_MappingEngine = new MappingEngine(configuration);
}
return _MappingEngine;
}
}
}
In my generic view I have mappingEngine property like this:
private IMappingEngine mappingEngine
{
get
{
if (_mappingEngine == null)
{
_mappingEngine = AutoMapper.Mapper.Engine;
}
return _mappingEngine;
}
}
Finally in my generic view constructor i have:
public GenericEntityController(IGenericLogic<S> logic, ICustomMapping customMapping)
: base()
{
this._mappingEngine = customMapping.MappingEngine;
this.logic = logic;
}
And that's how I do mapping:
result = items.Project(mappingEngine).To<R>();
or
logic.Update(mappingEngine.Map<S>(wsItem));
Because I use 1 entity per view I can define custom mapping configuration per entity.
Hope this helps
Related
I have below class LibrarySourceTableInput and having structure like as this
public class LibrarySourceTableInput<T> where T: ISourceOfData
{
public LibrarySourceTableInput(List<T> libraries, string mappedLibrarySource)
{
this.LibrarySourceRowInputs = libraries?.Select(l => new LibrarySourceRowInput()
{
LibrarySourceId = l.Id,
SourceOfDataId = l.SourceOfData.Id
}).ToList() ?? new(),
this.MappedLibrarySource = mappedLibrarySource;
}
public List<LibrarySourceRowInput> LibrarySourceRowInputs { get; set; }
public string MappedLibrarySource { get; set; }
}
and then the interface ISourceOfData structure looks like as this below
public interface ISourceOfData : IIdentity
{
public new Guid Id { get; set; }
public CodeStandardGuideline SourceOfData { get; set; }
}
And i am calling above class constructor in other place like as this
var mechanicalData = spaceTypeObject.TargetObject.MechanicalData;
var librarySourceTableInputs = new List<LibrarySourceTableInput<ISourceOfData>>
{
new LibrarySourceTableInput<ISourceOfData>(mechanicalData?.Environments, mappedLibrarySource), // I am getting conversion error here
new LibrarySourceTableInput<ISourceOfData>(mechanicalData?.AirflowsA621 , mappedLibrarySource)
.......
.......
}
and the structure for mechanicaldata.environments is looks like this
public class MechanicalData
{
public List<LibraryEnvironment> Environments { get; set; }
public List<LibraryA621> AirflowsA621 { get; set; }
.......
}
and then last one libraryEnvironment class is looks like this
public class LibraryEnvironment : ISourceOfData
{
public virtual CodeStandardGuideline SourceOfData { get; set; }
.....
......
public Guid Id {get; set;}
}
I have got the below error at this line new LibrarySourceTableInput<ISourceOfData>(mechanicalData?.Environments, mappedLibrarySource)
and the error is Cannot convert from Generic.List<LibraryEnvironment> to Generic.List<IsourceOfData>
Could any one please let me know or any idea on how to send that generic list to that class constructor, Many thanks in advance.
Instead of specifying the interface ISourceOfData (your class already knows the type will have that interface), specify the actual class:
var librarySourceTableInputs = new List<LibrarySourceTableInput<LibraryEnvironment>>
{
new LibrarySourceTableInput<LibraryEnvironment>(mechanicalData?.Environments, mappedLibrarySource),
.......
.......
}
I'm writing a tool which accesses a word document to prefill it with data. The document has a subset of custom document properties, each identified by a name, whose values are used to update fields in the document.
My ViewModel should both be able to initiate/update its instances from data of those document properties, aswell as write its values back and update the fields of the document.
Something like this:
class PersonVM : INotifyPropertyChanged
{
// properties
string Name { get; set; }
string PhoneNumber { get; set; }
// methods to get data or save data of this properties to or from the word document
void saveMyPropertyValuesToWord()
{
// …
}
void updateMyPropertiesFromWord()
{
// …
}
}
class ProjectVM : INotifyPropertyChanged
{
int ProjectNumber { get; set; }
PersonVM Manager { get; set; }
PersonVM Mechanic1 { get; set; }
PersonVM Mechanic2 { get; set; }
void saveMyPropertyValuesToWord()
{
Manager.saveMyPropertyValuesToWord();
Mechanic1.saveMyPropertyValuesToWord();
Mechanic2.saveMyPropertyValuesToWord();
// handle ProjectNumber etc.
}
void updateMyPropertiesFromWord()
{
Manager.updateMyPropertiesFromWord();
Mechanic1.updateMyPropertiesFromWord();
Mechanic2.updateMyPropertiesFromWord();
// handle ProjectNumber etc.
}
class CompanyVM : INotifyPropertyChanged
{
string Name { get; set; }
PersonVM Owner { get; set; }
ProjectVM Project1 { get; set; }
ProjectVM Project2 { get; set; }
// …
}
// …
}
Right now I have a class with static string properties for each document property that might be present in a word document from which I would like to load the data accordingly:
class WordUtils
{
// Company
static string CompanyName = "dp_CompanyName";
// Company.Owner
static string CompanyOwnerName = "dp_CompanyOwnerName";
static string CompanyOwnerPhone = "dp_CompanyOwnerPhone";
// Company.Project1
static string CompanyProject1Number = "dp_CompanyProject1Number";
// Company.Project1.Manager
static string CompanyProject1ManagerName = "dp_CompanyProject1ManagerName";
static string CompanyProject1ManagerPhone = "dp_CompanyProject1ManagerPhone";
// Company.Project1.Mechanic1
// … etc
}
Now back to implementing those PersonVM.saveMyPropertyValuesToWord() - I thought of something like this:
void saveMyPropertyValuesToWord()
{
Name = MyApp.MyWordDocument.GetCustomProperty(WordUtils.OwnerName);
}
but here I need to know on class Level exactly what instance of it this is called from (i.e. what PersonVM am I, Company.Owner or Project1.Manager or ?) in order to decide which WordUtils.Name I need to provide.
I'm not sure how this should be done, maybe make PersonVM abstract and make a new class for each role (which would again only have one instance of itself, not very pretty in my eyes)? I have also taken a short look at Attributes and expect those might be helpfull in this scenario. Maybe I am missing something obvious, but extensive search for a robust way to tackle this problem have been fruitless so far.
How about something like this:
class Property
{
public string Key { get; }
public string Value { get; set; }
public Property(string key) => Key = key;
}
interface IPropertyTree
{
IEnumerable<IPropertyTree> ChildNodes { get; }
IEnumerable<Property> Properties { get; }
}
class PersonVM : IPropertyTree
{
private readonly string prefix;
public PersonVM(string prefix)
{
Name = new Property(prefix + "Name" );
PhoneNumber = new Property(prefix + "PhoneNumber");
}
public Property Name { get; }
public Property PhoneNumber { get; }
public IEnumerable<IPropertyTree> ChildNodes => Enumerable.Empty<IPropertyTree>();
public IEnumerable<Property> Properties => new[] {Name, PhoneNumber};
}
static class PropertyTreeExtensions
{
public static void Update(this IPropertyTree self)
{
foreach (var property in self.Flatten().SelectMany(tree => tree.Properties))
{
property.Value = MyApp.MyWordDocument.GetCustomProperty(property.Key);
}
}
public static IEnumerable<IPropertyTree> Flatten(this IPropertyTree self)
{
var stack = new Stack<IPropertyTree>();
stack.Push(self);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
foreach (var child in current.ChildNodes)
{
stack.Push(child);
}
}
}
}
This should allow each property to have a unique key, and keep the key and property value tightly coupled. It should also allow you to move the save/update logic to a centralized place.
Of course you can implement a concrete class of IPerson for each type and hard code the individual implementations.
Since you know the person type the moment you are creating an instance of PersonVMM, you could add an attribute PersonTypeId and set it from the constructor,
void SomeMethod()
{
var personVm = new PersonVM(WordUtils.OwnerName);
}
class PersonVM : INotifyPropertyChanged
{
// properties
string PersonTypeId { get; set; }
string Name { get; set; }
string PhoneNumber { get; set; }
public PersonVM()
{}
public PersonVM(string personTypeId)
{
PersonTypeId = personTypeId;
}
// methods to get data or save data of this properties to or from the word document
void saveMyPropertyValuesToWord()
{
Name = MyApp.MyWordDocument.GetCustomProperty(PersonTypeId);
}
}
I have a profile setup like so:
public class DomainToViewModelProfile : Profile
{
public DomainToViewModelProfile()
{
CreateMap<DataPrivacy, DataPrivacyViewModel>();
CreateMap<DeliveryStage, DeliveryStageViewModel>();
CreateMap<FundedState, FundedStateViewModel>();
CreateMap<Gate, GateViewModel>();
CreateMap<Location, LocationViewModel>();
CreateMap<PersonRole, PersonRoleViewModel>();
CreateMap<Person, PersonViewModel>();
CreateMap<ProjectGate, ProjectGateViewModel>();
CreateMap<ProjectStatus, ProjectStatusViewModel>();
CreateMap<RadarProject, RadarProjectViewModel>();
CreateMap<ManualData, ManualDataViewModel>();
}
}
I, now, have a new model to map nut it is just a class with two properties that are the last two mappings above:
public class DesignProjectViewModel
{
public DesignProjectViewModel()
{
}
public DesignProjectViewModel(RadarProjectViewModel radar, ManualDataViewModel manual)
{
RadarProject = radar;
ManualDataProject = manual;
}
public DesignProjectViewModel(DesignProjectViewModel model)
{
RadarProject = model.RadarProject;
ManualDataProject = model.ManualDataProject;
}
public RadarProjectViewModel RadarProject { get; set; }
public ManualDataViewModel ManualDataProject { get; set; }
}
How do I create a map for this class?
Started to learn asp.net and DB manipulations. Trying to implement some simple functionality - two models, one has list of references to another.
Here is an error that I currently get:
An exception occurred while initializing the database. See the InnerException for details.
Inner exception:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
My models:
public class Killer
{
public Killer(string name, string biography)
{
Name = name;
Biography = biography;
KillerId = Guid.NewGuid();
}
public Guid KillerId { get; set; }
public string Name { get; set; }
public string Biography { get; set; }
public virtual Contract Contract { get; set; }
}
public class Contract
{
public Contract(Status status, Killer target, string description, params Killer[] targets)
{
ContractId = Guid.NewGuid();
this.status = status;
Target = target;
Description = description;
Killers = new HashSet<Killer>();
foreach (var t in targets) Killers.Add(t);
}
public Guid ContractId { get; set; }
public enum Status { active, done, failed, rejected, abandoned }
public Status status { get; set; }
public Killer Target { get; set; }
public string Description { get; set; }
//[ForeignKey("ContractID")]
public virtual ICollection<Killer> Killers { get; set; }
}
In context I initialize db with lists of objects
public class KillerContext : DbContext
{
public DbSet<Killer> Killers { get; set; }
public DbSet<Contract> Contracts { get; set; }
}
In controller I do:
KillerContext k = new KillerContext();
public ActionResult Index()
{
var contracts = k.Contracts.ToList();
ViewBag.contracts = contracts;
return View();
}
In Global.asax:
Database.SetInitializer(new KillerContextInitialization());
Here is how I enter first data in db:
public sealed class KillerContextInitialization : DropCreateDatabaseAlways<KillerContext>
{
protected override void Seed(KillerContext db)
{
List<Killer> killers = new List<Killer>();
//List<Contract> contracts = new List<Contract>();
killers.Add(new Killer(name: "Ivan Firstein", biography: "He was born in the shadows."));
killers.Add(new Killer(name: "Oleg Gazmanov", biography: "test man"));
db.Contracts.Add(new Contract(
Contract.Status.active,
killers.SingleOrDefault(x => x.Name == "Ivan Firstein"),
"KILL OR BE KILLED. As always with love.",
killers.SingleOrDefault(x => x.Name == "Oleg Gazmanov")
));
db.Killers.AddRange(killers);
base.Seed(db);
}
}
Looks like you need add ForeignKey attribute for killer Model, and store this key in property ContractId:
public class Killer
{
[ForeignKey(nameof(ContractId)] //Name of added property in line below
public Contract Contract { get; set; } //no need "virtual"
public Guid? ContractId { get; set; }
// other properties...
}
public class Contract
{
[ForeignKey("ContractId")] //Name of added property in Killer Model
public virtual ICollection<Killer> Killers { get; set; }
// other code...
}
EDIT
You should do something similar to the Contract.Target property:
[ForeignKey(nameof(TargetId)]
public Killer Target { get; set; }
public Guid TargetId { get; set; }
For enum types you should add attributes like this:
[Column(nameof(status), TypeName = "int")]
public Status status { get; set; }
Find out that problem was in public Killer Target { get; set; }
When i was adding data, that field was considered as NOT NULL, and all what i need to do, is save changes after filling killers, like so:
public sealed class KillerContextInitialization : DropCreateDatabaseAlways<KillerContext>
{
protected override void Seed(KillerContext db)
{
List<Killer> killers = new List<Killer>();
killers.Add(new Killer(name: "Ivan Firstein", biography: "He was born in the shadows."));
killers.Add(new Killer(name: "Oleg Gazmanov", biography: "test man"));
db.SaveChanges(); // - save killers first, then add them to contract
db.Contracts.Add(new Contract(
Contract.Status.active,
killers.SingleOrDefault(x => x.Name == "Ivan Firstein"),
"KILL OR BE KILLED. As always with love.",
killers.SingleOrDefault(x => x.Name == "Oleg Gazmanov")
));
db.Killers.AddRange(killers);
base.Seed(db);
}
}
Here is my data transfer object
public class LoadSourceDetail
{
public string LoadSourceCode { get; set; }
public string LoadSourceDesc { get; set; }
public IEnumerable<ReportingEntityDetail> ReportingEntity { get; set; }
}
public class ReportingEntityDetail
{
public string ReportingEntityCode { get; set; }
public string ReportingEntityDesc { get; set; }
}
And here is my ViewModel
public class LoadSourceViewModel
{
#region Construction
public LoadSourceViewModel ()
{
}
public LoadSourceViewModel(LoadSourceDetail data)
{
if (data != null)
{
LoadSourceCode = data.LoadSourceCode;
LoadSourceDesc = data.LoadSourceDesc;
ReportingEntity = // <-- ? not sure how to do this
};
}
#endregion
public string LoadSourceCode { get; set; }
public string LoadSourceDesc { get; set; }
public IEnumerable<ReportingEntityViewModel> ReportingEntity { get; set; }
}
public class ReportingEntityViewModel
{
public string ReportingEntityCode { get; set; }
public string ReportingEntityDesc { get; set; }
}
}
I'm not sure how to transfer the data from the LoadSourceDetail ReportingEntity to the LoadSourceViewModel ReportingEntity. I'm trying to transfer data from one IEnumerable to another IEnumerable.
I would use AutoMapper to do this:
https://github.com/AutoMapper/AutoMapper
http://automapper.org/
You can easily map collections, see https://github.com/AutoMapper/AutoMapper/wiki/Lists-and-arrays
It would look something like this:
var viewLoadSources = Mapper.Map<IEnumerable<LoadSourceDetail>, IEnumerable<LoadSourceViewModel>>(loadSources);
If you are using this in an MVC project I usually have an AutoMapper config in the App_Start that sets the configuration i.e. fields that do not match etc.
Without AutoMapper you will have to map each property one by one ,
Something like this :
LoadSourceDetail obj = FillLoadSourceDetail ();// fill from source or somewhere
// check for null before
ReportingEntity = obj.ReportingEntity
.Select(x => new ReportingEntityViewModel()
{
ReportingEntityCode = x.ReportingEntityCode,
ReportingEntityDesc x.ReportingEntityDesc
})
.ToList(); // here is 'x' is of type ReportingEntityDetail
You could point it to the same IEnumerable:
ReportingEntity = data.ReportingEntity;
If you want to make a deep copy, you could use ToList(), or ToArray():
ReportingEntity = data.ReportingEntity.ToList();
That will materialize the IEnumerable and store a snapshot in your view model.