I'd like to map from a flattened object to a hierarchical object based on a simple naming convention. For example:
public class FlatObject {
public string Name__FirstName { get; set; }
public string Name__MiddleName { get; set; }
public string Name__LastName { get; set; }
}
public class HierarchicalObject {
public SubObject Name { get; set; }
}
public class SubObject {
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
The simple naming convention is the double-underscore within the FlattenedObject.
How would I accomplish this using EmitMapper?
EmitMapper cannot do this task without significant code changes.
Related
With the Model
public class Person {
public string Forename { get; set; }
public string Surname { get; set; }
public string DOB { get; set; }
}
I have a ViewModel which I'll be passing through to the View
public class PersonViewModel {
public IQueryable<Person> PersonVM { get; set; }
public string sometext{ get; set; }
}
If, for example, I wanted to calculate the age in the controller code and store it against each Person row in the IQueryable so it could be seen in the View, what's the best way of adding an Age property to each row?
I'm guessing that I don't have to include a fake property in the Person model like so
public string Age { get; set; }
You can use the NotMapped attribute which will exclude the property from database mapping.
public class Person
{
public string Forename { get; set; }
public string Surname { get; set; }
public string DOB { get; set; }
[NotMapped]
public string Age { get; set; }
}
You can make Age property set private and write your logic in get to calculate it at run time.
public class Person {
public string Forename { get; set; }
public string Surname { get; set; }
public string DOB { get; set; }
public string Age {
get{
//.... you logic
}
private set{}
}
I have the following db structure:
I am using EF6 to create the entities from database and have the following classes created by EF6:
public partial class Mechanic
{
public Mechanic()
{
this.MechanicAddresses = new HashSet<MechanicAddress>();
this.MechanicServices = new HashSet<MechanicService>();
}
public string ID { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string MobileNumber { get; set; }
public Nullable<bool> IsMobile { get; set; }
public string Url { get; set; }
public string FaceBookUrl { get; set; }
public string TwitterUrl { get; set; }
public string Description { get; set; }
public string Discriminator { get; set; }
public bool IsEnabled { get; set; }
public bool IsAuthorised { get; set; }
public string Logo { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public virtual ICollection<MechanicAddress> MechanicAddresses { get; set; }
public virtual ICollection<MechanicService> MechanicServices { get; set; }
}
public partial class MechanicAddress
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string District { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public int CountryId { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public bool IsPrimary { get; set; }
public Nullable<double> Latitude { get; set; }
public Nullable<double> Longitude { get; set; }
public System.Data.Entity.Spatial.DbGeography Location { get; set; }
public virtual Country Country { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
public partial class MechanicService
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string Service { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
The data is correct so i expect to get data in all entities.
When i run the following linq query in my DAL:
Mechanic mech = context.Mechanics.Where(a => a.ID == id).Include(a => a.MechanicAddresses).Include(a => a.MechanicServices).FirstOrDefault();
It returns the mechanic and mechanicAddresses but mechanicServices is always empty (count == 0).
When i run the same query in LinqPad I get all entities filled as expected.
I have removed the edmx and re-created it but still get the same issue.
Please check if "MultipleActiveResultSets" is set to true and LazyLoadingEnabled is enabled in connection string. It may help.
And what about your OnModelCreating?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
It's not necessary to use Include if you have LazyLoading (virtual). And If it works fine in LinqPad try to do migration into empty DB (just test). And then try to get data from test DB.
The only way i was able to resolve this was to:
delete the EDMX
script the create for the mechanicsServices table
script the data
drop the mechanicsServices table
run the create table script from above
run the insert data script
regenerate the EDMX
This now works, WTF! Can't explain it.
I know it's always best to understand what went wrong but this one beat me.
I had same problem.
If you using git, please check .edmx file old version. SSDL content may be missing.
I have a client class that I need to map to a less complexe class of clientViewModel, and here are the two classes:
public class client
{
public int clientRef{get;set;}
public string Title{get;set;}
public string Forename { get; set; }
public string Initials { get; set; }
public string Surname { get; set; }
Public Address address{get;set;}
}
and
public class ClientsViewModel
{
public int ClientRef { get; set; }
public string Title { get; set; }
public string Forename { get; set; }
public string Initials { get; set; }
public string Surname { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
}
And this si how I mapped the model(It is just still a proof of concept)
IList<ClientsViewModel> _clientsViewModelsclients = new List<ClientsViewModel>();
var model =
new Clients().Get(10);
Mapper.CreateMap<Client, ClientsViewModel>();
ClientsViewModel cv = Mapper.Map<Client, ClientsViewModel>(model);
_clientsViewModelsclients.Add(cv);
return View(_clientsViewModelsclients);
thr problem is on the view I can see the name and title but not the Address. Is there any other mapping I should be doing, t make sure that whatever is in address line 1 odf the address class is mapped to Line1 of the clientViewModel class?
Thanks
From the comments
Take a look here: http://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings or you can create a custom resolver.. http://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers
I am getting a weird behavior. I have a class that I created that is used to format data comping from a data entity into a data grid. I am a using a linq query to create a list of the class type from a list of the entity type. Some of the properties of the class are accessible from the linq query but other give me an error. (AMNotStartedPortalDisplay' does not contain a definition for 'ChecklistStatusID'). So my question is why can linq access some properties but not others? I see no reason why this should be happening.
Here is my class:
public class AMWOTPortalDisplay
{
public string DisplayName { get; set; }
public string LOB { get; set; }
public string DisplayProjectPackages { get; set; }
public string ChecklistStatus { get; set; }
public int ChecklistStatusID { get; set; }
public string InstallDate { get; set; }
public string dateToYellow { get; set; }
public string dateToRed { get; set; }
public string ApplicationManager { get; set; }
public string ApplicationManagerLanID { get; set; }
public int ApplicationManagerUserID { get; set; }
public string ImpersonatedManager { get; set; }
public string ImpersonatedManagerLanID { get; set; }
public int ImpersonatedManagerUserID { get; set; }
public string DelegateName { get; set; }
public string DelegateLanID { get; set; }
public int DelegateUserID { get; set; }
public string WOTAssignee { get; set; }
public int ChecklistID { get; set; }
public string DisplayLinkText { get; set; }
public string LinkTextURL { get; set; }
public string rowColor { get; set; }
public string rowTextColor { get; set; }
}
And here is the linq query as I have it so far:
var portaldisplay = checklists
.Select(c => new AMNotStartedPortalDisplay
{
DisplayName = string.Format("{0} ({1})", c.Application.Name, c.Application.ApplicationID),
LOB = c.Application.LOB,
ChecklistStatus = c.ChecklistStatusType.TypeName,
ChecklistStatusID = c.ChecklistStatusTypeID
});
Thanks,
Rhonda
Be careful with your types:
public class AMWOTPortalDisplay
And then:
Select(c => new AMNotStartedPortalDisplay { ... })
It looks like your query should probably be:
Select(c => new AMWOTPortalDisplay { ... })
I have a handful of email templates and in each template I have a header and footer that all share the same info.
The header and footer are represented by EmailModel.cs
public class EmailModel
{
public string CompanyName { get { return ConfigurationManager.AppSettings["CompanyName"]; } }
public string PhoneNumber { get { return ConfigurationManager.AppSettings["PhoneNumber"]; } }
public string FacebookUrl { get { return ConfigurationManager.AppSettings["FacebookUrl"]; } }
public string TwitterUrl { get { return ConfigurationManager.AppSettings["TwitterUrl"]; } }
public string YouTubeUrl { get { return ConfigurationManager.AppSettings["YouTubeUrl"]; } }
//Additional methods for sending these templates as emails
}
Now for a specific email template I have a view model.NewSignUpEmailViewModel.cs
Should I do this:
public class NewSignUpEmailViewModel : EmailModel
{
public string FirstName { get; set; }
public string CompanyName { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
}
or this:
public class NewSignUpEmailViewModel
{
public EmailModel Email {get; set;}
public string FirstName { get; set; }
public string CompanyName { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
}
I just used email as an example, is there pros/cons to each?
The only con I can see is that in some cases you will run into duplicate property name issue.
Composition is often preferred over inheritance, but both have their place. One good rule of thumb is to determine if there is an "is-a" or a "has-a" relationship between your objects. If object 1 has object 2 as a component, composition is definitely the way to go.
As an example, let's approach your data model a bit differently:
public class SocialLinks
{
public string FacebookUrl { get; set; }
public string TwitterUrl { get; set; }
public string YouTubeUrl { get; set; }
}
public class User
{
public SocialLinks links { get; set; }
public string Name { get; set; }
// and so on
}
In this example, it's obvious that a user HAS social web links, as opposed to the user being a specialized version of the SocialLinks class. Hope that helps!