How to map objects - c#

Here is my how my bindings currently look:
MerchantAccountRequest request = new MerchantAccountRequest
{
Individual = new IndividualRequest
{
FirstName = merchant.MerchantIndividual.FirstName,
LastName = merchant.MerchantIndividual.LastName,
Email = merchant.MerchantIndividual.Email,
Phone = merchant.MerchantIndividual.Phone,
DateOfBirth = merchant.MerchantIndividual.DateOfBirth,
Ssn = merchant.MerchantIndividual.Ssn,
Address = new AddressRequest
{
StreetAddress = merchant.MerchantIndividual.StreetAddress,
Locality = merchant.MerchantIndividual.Locality,
Region = merchant.MerchantIndividual.Region,
PostalCode = merchant.MerchantIndividual.PostalCode
}
},
Business = new BusinessRequest
{
LegalName = merchant.MerchantBusiness.LegalName,
DbaName = merchant.MerchantBusiness.DbaName,
TaxId = merchant.MerchantBusiness.TaxId,
Address = new AddressRequest
{
StreetAddress = merchant.MerchantBusiness.StreetAddress,
Locality = merchant.MerchantBusiness.Locality,
Region = merchant.MerchantBusiness.Region,
PostalCode = merchant.MerchantBusiness.PostalCode
}
},
Funding = new FundingRequest
{
Descriptor = merchant.MerchantFunding.Descriptor,
Destination = FundingDestination.BANK,
Email = merchant.MerchantFunding.Email,
MobilePhone = merchant.MerchantFunding.MobilePhone,
AccountNumber = merchant.MerchantFunding.AccountNumber,
RoutingNumber = merchant.MerchantFunding.RoutingNumber
},
TosAccepted = merchant.TosAccepted,
MasterMerchantAccountId = merchant.MasterMerchantAccountId,
Id = merchant.MerchantId
};
And I need to use AutoMapper to achieve the above.
This is what I've tried:
CreateMapperProfile
EDIT:
CreateMap<Classes.Merchant, MerchantAccountRequest>()
.ForMember(dest => dest.Individual, source => source.MapFrom(s => s.MerchantIndividual))
.ForMember(dest => dest.Business, source => source.MapFrom(s => s.MerchantBusiness))
.ForMember(dest => dest.Funding, source => source.MapFrom(s => s.MerchantFunding))
.ForMember(dest => dest.Id, source => source.MapFrom(s => s.MerchantId));
Here is the Merchant class:
public partial class Merchant :
{
public int Id { get; set; }
public string MerchantId { get; set; }
public virtual MerchantIndividual MerchantIndividual { get; set; }
public virtual MerchantBusiness MerchantBusiness { get; set; }
public virtual MerchantFunding MerchantFunding { get; set; }
public bool TosAccepted { get; set; }
public string MasterMerchantAccountId { get; set; }
public bool isSubMerchant { get; set; }
}
And the mappings;
EDIT:
MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant);
request.Individual = _mapper.Map<IndividualRequest>(merchant.MerchantIndividual);
request.Business = _mapper.Map<BusinessRequest>(merchant.MerchantBusiness);
request.Funding = _mapper.Map<FundingRequest>(merchant.MerchantFunding);
Can the first line of code MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant); above do all the mapings?
..
..
..
..
How can I create the correct mappings?

You don't need to call _mapper.Map on the properties of the request.
Just call MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant); and assuming you have a map for each type you should be fine.
I think something along the lines of the following should get you going down the right path.
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Merchant, MerchantAccountRequest>()
.ForMember(dest => dest.Individual, c => c.MapFrom(source => source.MerchantIndividual));
cfg.CreateMap<MerchantIndividual, IndividualRequest>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var merchant = new Merchant
{
Id = 1,
MerchantIndividual = new MerchantIndividual { FirstName = "John Doe" }
};
var merchantAccountRequest = mapper.Map<Merchant, MerchantAccountRequest>(merchant);
}
}
public class Merchant
{
public int Id { get; set; }
public MerchantIndividual MerchantIndividual { get; set; }
}
public class MerchantIndividual
{
public string FirstName { get; set; }
}
public class MerchantAccountRequest
{
public int Id { get; set; }
public IndividualRequest Individual { get; set; }
}
public class IndividualRequest
{
public string FirstName { get; set; }
}

Related

C# Bad Performance OData when using extension

I have a Web API for OData services. I have a lot of table with many relations. Here is some of the table:
MSADDRESSCOUNTRY
public partial class MSADDRESSCOUNTRY
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage","CA2214:DoNotCallOverridableMethodsInConstructors")]
public MSADDRESSCOUNTRY()
{
this.MSADDRESSPROVINCEs = new HashSet<MSADDRESSPROVINCE>();
}
public int ID { get; set; }
public string CODE { get; set; }
public string COUNTRYNAME { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage","CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MSADDRESSPROVINCE> MSADDRESSPROVINCEs { get; set; }
}
MSADDRESSPROVINCE
public partial class MSADDRESSPROVINCE
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MSADDRESSPROVINCE()
{
this.MSADDRESSDISTRICTs = new HashSet<MSADDRESSDISTRICT>();
}
public int ID { get; set; }
public Nullable<int> COUNTRYID { get; set; }
public string PROVINCENAME { get; set; }
public virtual MSADDRESSCOUNTRY MSADDRESSCOUNTRY { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage","CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MSADDRESSDISTRICT> MSADDRESSDISTRICTs { get; set; }
}
MSADDRESSDISTRICT
public partial class MSADDRESSDISTRICT
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MSADDRESSDISTRICT()
{
this.MSADDRESSSUBDISTRICTs = new HashSet<MSADDRESSSUBDISTRICT>();
}
public int ID { get; set; }
public Nullable<int> PROVINCEID { get; set; }
public string DISTRICTNAME { get; set; }
public virtual MSADDRESSPROVINCE MSADDRESSPROVINCE { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MSADDRESSSUBDISTRICT> MSADDRESSSUBDISTRICTs { get; set; }
}
I create DTO object model for every table with the property is the same with Database object model.
I want the client can use $expand keyword to get child data and/or parent data.
For MSADDRESSCOUNTRY I need to write the code like this.
[EnableQuery(MaxExpansionDepth = 4)]
public IQueryable<MsAddressCountryObject> Get()
{
return db.MSADDRESSCOUNTRies.Select(c => new MsAddressCountryObject
{
ID = c.ID,
CODE = c.CODE,
COUNTRYNAME = c.COUNTRYNAME,
MSADDRESSPROVINCEs = c.MSADDRESSPROVINCEs.Select(data => new MsAddressProvinceObject()
{
ID = data.ID,
COUNTRYID = data.COUNTRYID,
PROVINCENAME = data.PROVINCENAME,
MSADDRESSCOUNTRY = new MsAddressCountryObject()
{
ID = data.MSADDRESSCOUNTRY.ID,
CODE = data.MSADDRESSCOUNTRY.CODE,
COUNTRYNAME = data.MSADDRESSCOUNTRY.COUNTRYNAME,
},
MSADDRESSDISTRICTs = data.MSADDRESSDISTRICTs.Select(dist => new MsAddressDistrictObject()
{
ID = dist.ID,
PROVINCEID = dist.PROVINCEID,
DISTRICTNAME = dist.DISTRICTNAME,
})
})
});
}
For MSADDRESSPROVINCE I need to write the code like this.
[EnableQuery(MaxExpansionDepth = 4)]
public IQueryable<MsAddressProvinceObject> Get()
{
return db.MSADDRESSPROVINCEs.Select(data => new MsAddressProvinceObject()
{
ID = data.ID,
COUNTRYID = data.COUNTRYID,
PROVINCENAME = data.PROVINCENAME,
MSADDRESSCOUNTRY = new MsAddressCountryObject()
{
ID = data.MSADDRESSCOUNTRY.ID,
CODE = data.MSADDRESSCOUNTRY.CODE,
COUNTRYNAME = data.MSADDRESSCOUNTRY.COUNTRYNAME,
},
MSADDRESSDISTRICTs = data.MSADDRESSDISTRICTs.Select(dist => new MsAddressDistrictObject()
{
ID = dist.ID,
PROVINCEID = dist.PROVINCEID,
DISTRICTNAME = dist.DISTRICTNAME
})
});
}
That code works fast. But if I add/change/remove column, I have to modify the controller manually, one by one for all controller. For example, if I want to add geological coordinate in MSADDRESSDISTRICT, I have to change the code in Country Controller, Province Controller and District Controller.
So I decide to create extension method like this.
public static MsAddressCountryObject ToDTO(this MSADDRESSCOUNTRY data)
{
return new MsAddressCountryObject()
{
ID = data.ID,
CODE = data.CODE,
COUNTRYNAME = data.COUNTRYNAME,
};
}
public static IQueryable<MsAddressCountryObject ToDTO(this IEnumerable<MSADDRESSCOUNTRY datas)
{
return datas.Select(country =
{
var obj = country?.ToDTO();
obj.MSADDRESSPROVINCEs = country.MSADDRESSPROVINCEs?.ToDTO();
return obj;
}).AsQueryable();
}
public static MsAddressProvinceObject ToDTO(this MSADDRESSPROVINCE data)
{
return new MsAddressProvinceObject()
{
ID = data.ID,
COUNTRYID = data.COUNTRYID,
PROVINCENAME = data.PROVINCENAME,
MSADDRESSCOUNTRY = data.MSADDRESSCOUNTRY?.ToDTO()
};
}
public static IQueryable<MsAddressProvinceObject ToDTO(this IEnumerable<MSADDRESSPROVINCE datas)
{
return datas.Select(province =
{
var obj = province?.ToDTO();
obj.MSADDRESSDISTRICTs = province.MSADDRESSDISTRICTs.ToDTO();
return obj;
}).AsQueryable();
}
public static MsAddressDistrictObject ToDTO(this MSADDRESSDISTRICT data)
{
return new MsAddressDistrictObject()
{
ID = data.ID,
PROVINCEID = data.PROVINCEID,
DISTRICTNAME = data.DISTRICTNAME,
MSADDRESSPROVINCE = data.MSADDRESSPROVINCE?.ToDTO()
};
}
public static IQueryable<MsAddressDistrictObject ToDTO(this IEnumerable<MSADDRESSDISTRICT datas)
{
return datas.Select(district =
{
var obj = district?.ToDTO();
obj.MSADDRESSSUBDISTRICTs = district.MSADDRESSSUBDISTRICTs?.ToDTO();
return obj;
}).AsQueryable();
}
And the controller just like this.
[EnableQuery(MaxExpansionDepth = 4)]
public IQueryable<MsAddressCountryObject Get()
{
return db.MSADDRESSCOUNTRies.ToDTO()
}
And that makes the performance really bad. I think the extension is making a lot of memory allocation or some thing that make the result not being delivered directly to the client.
My goal is to create the code easy to maintain, and the performance not drop significantly.
I have many relation in other table. I want the $expand works without write all parent/child Select statement manually and one by one.
I have try to not calling ToDTO() from all the extension method. The result is the performance is fast. But I lost all the relation or I need to write the parent/child Select statement for all method.
Any suggestion will help.
Thanks.

EF Data setting ViewModel

I have a ViewModel where objects are all string and the model from the database Address is a list. I wanted to know if there is any other way to set the viewModel string values other then the way I have it done below? Any advice on how I can combine the two ListOfProducts.Select lines?
static void Main(string[] args)
{
//EF Data
List<Address> ListOfProducts = new List<Address>();
ListOfProducts.Add(new Address() { StreetLine1="address 1",StreetLine2="address line2 1" });
ViewModelAddress vm = new ViewModelAddress();
vm.StreetLine1 = ListOfProducts.Select(a => a.StreetLine1).FirstOrDefault();
vm.StreetLine2 = ListOfProducts.Select(a => a.StreetLine2).FirstOrDefault();
}
class Address
{
public string StreetLine1 { get; set; }
public string StreetLine2{ get; set; }
}
class ViewModelAddress
{
public string StreetLine1 { get; set; }
public string StreetLine2 { get; set; }
}
var vm = ListOfProducts.Select(a => new ViewModelAddress
{StreetLine1 = a.StreetLine1, StreetLine2 = a.StreetLine2}).FirstOrDefault();

Get 1 record from 2 tables ASP.NET

I am still an ASP.NET amateur and I've been working on an application that needs to calculate the hours an employee has worked if no special events have come up e.g the employee has been sick, I have 2 tables in my database, 1 with the employees. and a second table which holds the events. the events table is filled through a calendar and holds info like dates and who made the event.
My situation:
When the user clicks on an employee's detail page. I want the corresponding record of the employee, and the events he made. So I am assuming that I am looking for a join with linq.
An employee can make more than 1 event, let's say an employee needs to work overtime 3 days this month. then on the detail page, it should select the employee from the employee table and the 3 events from the events table.
Update
Thanks to Vladimir's help, a whole lot of errors are gone and the query works. Though it does not completely work as expected yet. it currently returns 1 employee and 1 event. While the employee that I am testing with, should have 4 events returned.
This is my Context
namespace hrmTool.Models
{
public class MedewerkerMeldingContext : DbContext
{
public MedewerkerMeldingContext() : base("name=temphrmEntities") { }
public DbSet<medewerker> medewerker { get; set; }
public DbSet<medewerker_melding> medewerker_melding { get; set; }
}
}
My current viewModel
namespace hrmTool.Models
{
public class MedewerkerMeldingViewModel
{
//Medewerker tabel
public int ID { get; set; }
public string roepnaam { get; set; }
public string voorvoegsel { get; set; }
public string achternaam { get; set; }
public string tussenvoegsel { get; set; }
public string meisjesnaam { get; set; }
public Nullable<System.DateTime> datum_in_dienst { get; set; }
public Nullable<System.DateTime> datum_uit_dienst { get; set; }
public int aantal_km_woon_werk { get; set; }
public bool maandag { get; set; }
public Nullable<System.TimeSpan> ma_van { get; set; }
public Nullable<System.TimeSpan> ma_tot { get; set; }
public bool dinsdag { get; set; }
public Nullable<System.TimeSpan> di_van { get; set; }
public Nullable<System.TimeSpan> di_tot { get; set; }
public bool woensdag { get; set; }
public Nullable<System.TimeSpan> wo_van { get; set; }
public Nullable<System.TimeSpan> wo_tot { get; set; }
public bool donderdag { get; set; }
public Nullable<System.TimeSpan> do_van { get; set; }
public Nullable<System.TimeSpan> do_tot { get; set; }
public bool vrijdag { get; set; }
public Nullable<System.TimeSpan> vr_van { get; set; }
public Nullable<System.TimeSpan> vr_tot { get; set; }
public bool zaterdag { get; set; }
public Nullable<System.TimeSpan> za_van { get; set; }
public Nullable<System.TimeSpan> za_tot { get; set; }
public bool zondag { get; set; }
public Nullable<System.TimeSpan> zo_van { get; set; }
public Nullable<System.TimeSpan> zo_tot { get; set; }
//Medewerker_Melding combi tabel
public int medewerkerID { get; set; }
public int meldingID { get; set; }
public System.DateTime datum_van { get; set; }
public Nullable<System.DateTime> datum_tot { get; set; }
public int MM_ID { get; set; }
public virtual ICollection<medewerker_melding> medewerker_melding { get; set; }
public virtual medewerker medewerker { get; set; }
}
}
My current query
using (var context = new MedewerkerMeldingContext())
{
var medewerkers = context.medewerker;
var medewerker_meldings = context.medewerker_melding;
var testQuery = from m in medewerkers
join mm in medewerker_meldings on m.ID equals mm.medewerkerID
where m.ID == id
select new MedewerkerMeldingViewModel
{
ID = m.ID,
roepnaam = m.roepnaam,
voorvoegsel = m.voorvoegsel,
achternaam = m.achternaam,
tussenvoegsel = m.tussenvoegsel,
meisjesnaam = m.meisjesnaam,
datum_in_dienst = m.datum_in_dienst,
datum_uit_dienst = m.datum_uit_dienst,
aantal_km_woon_werk = m.aantal_km_woon_werk,
maandag = m.maandag,
ma_van = m.ma_van,
ma_tot = m.ma_tot,
dinsdag = m.dinsdag,
di_van = m.di_van,
di_tot = m.di_tot,
woensdag = m.woensdag,
wo_van = m.wo_van,
wo_tot = m.wo_tot,
donderdag = m.donderdag,
do_van = m.do_van,
do_tot = m.do_tot,
vrijdag = m.vrijdag,
vr_van = m.vr_van,
vr_tot = m.vr_tot,
zaterdag = m.zaterdag,
za_van = m.za_van,
za_tot = m.za_tot,
zondag = m.zondag,
zo_van = m.zo_van,
zo_tot = m.zo_tot,
medewerkerID = mm.medewerkerID,
meldingID = mm.meldingID,
datum_van = mm.datum_van,
datum_tot = mm.datum_tot,
MM_ID = mm.ID
};
var getQueryResult = testQuery.FirstOrDefault();
Debug.WriteLine("Debug testQuery" + testQuery);
Debug.WriteLine("Debug getQueryResult: "+ getQueryResult);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (testQuery == null)
{
return HttpNotFound();
}
return View(getQueryResult);
}
Returns: 1 instance of employee and only 1 event
Expected return: 1 instance of employee, 4 events
In your context DbContext is missing - so Linq to Entity can not find corresponding implementation of the query. And also DbContext operates with the
DbSets - so try:
public class MedewerkerMeldingContext : DbContext
{
public MedewerkerMeldingContext () : base(ConnectionStringKey)
{
};
public DbSet<medewerker> medewerker { get; set; }
public DbSet<medewerker_melding> medewerker_melding { get; set; }
}
then
using (var context = new MedewerkerMeldingContext())
{
var medewerkers = context.medewerker;
var medewerker_meldings = context.medewerker_melding;
var testQuery = from m in medewerkers
join mm in medewerker_meldings on m.ID equals mm.medewerkerID
where m.ID == id
select new MedewerkerMeldingViewModel
{
ID = m.ID,
roepnaam = m.roepnaam,
voorvoegsel = m.voorvoegsel,
achternaam = m.achternaam,
tussenvoegsel = m.tussenvoegsel,
meisjesnaam = m.meisjesnaam,
datum_in_dienst = m.datum_in_dienst,
datum_uit_dienst = m.datum_uit_dienst,
aantal_km_woon_werk = m.aantal_km_woon_werk,
maandag = m.maandag,
ma_van = m.ma_van,
ma_tot = m.ma_tot,
dinsdag = m.dinsdag,
di_van = m.di_van,
di_tot = m.di_tot,
woensdag = m.woensdag,
wo_van = m.wo_van,
wo_tot = m.wo_tot,
donderdag = m.donderdag,
do_van = m.do_van,
do_tot = m.do_tot,
vrijdag = m.vrijdag,
vr_van = m.vr_van,
vr_tot = m.vr_tot,
zaterdag = m.zaterdag,
za_van = m.za_van,
za_tot = m.za_tot,
zondag = m.zondag,
zo_van = m.zo_van,
zo_tot = m.zo_tot,
medewerkerID = mm.medewerkerID,
meldingID = mm.meldingID,
datum_van = mm.datum_van,
datum_tot = mm.datum_tot,
MM_ID = mm.ID
};
Debug.WriteLine("Debug testQuery" + testQuery);
var getQueryResult = testQuery.ToList();
Debug.WriteLine("Debug getQueryResult: " + getQueryResult);
var resultDictionary = getQueryResult.GroupBy(x => x.ID).ToDictionary(y => y.Key, z => z.ToList());
Debug.WriteLine("resultDictionary: " + resultDictionary);
var firstItem = resultDictionary.Values.First();
Debug.WriteLine("FirstItem: " + firstItem);
var Entity = new newEntity
{
//ID = firstItem.ID,
ID = firstItem.Select(x => x.ID).First(),
roepnaam = firstItem.Select(x => x.roepnaam).First(),
voorvoegsel = firstItem.Select(x => x.voorvoegsel).First(),
achternaam = firstItem.Select(x => x.achternaam).First(),
tussenvoegsel = firstItem.Select(x => x.tussenvoegsel).First(),
meisjesnaam = firstItem.Select(x => x.meisjesnaam).First(),
datum_in_dienst = firstItem.Select(x => x.datum_in_dienst).First(),
datum_uit_dienst = firstItem.Select(x => x.datum_uit_dienst).First(),
aantal_km_woon_werk = firstItem.Select(x => x.aantal_km_woon_werk).First(),
maandag = firstItem.Select(x => x.maandag).First(),
ma_van = firstItem.Select(x => x.ma_van).First(),
ma_tot = firstItem.Select(x => x.ma_tot).First(),
dinsdag = firstItem.Select(x => x.dinsdag).First(),
di_van = firstItem.Select(x => x.di_van).First(),
di_tot = firstItem.Select(x => x.di_tot).First(),
woensdag = firstItem.Select(x => x.woensdag).First(),
wo_van = firstItem.Select(x => x.wo_van).First(),
wo_tot = firstItem.Select(x => x.wo_tot).First(),
donderdag = firstItem.Select(x => x.donderdag).First(),
do_van = firstItem.Select(x => x.do_van).First(),
do_tot = firstItem.Select(x => x.do_tot).First(),
vrijdag = firstItem.Select(x => x.vrijdag).First(),
vr_van = firstItem.Select(x => x.vr_van).First(),
vr_tot = firstItem.Select(x => x.vr_tot).First(),
zaterdag = firstItem.Select(x => x.zaterdag).First(),
za_van = firstItem.Select(x => x.za_van).First(),
za_tot = firstItem.Select(x => x.za_tot).First(),
zondag = firstItem.Select(x => x.zondag).First(),
zo_van = firstItem.Select(x => x.zo_van).First(),
zo_tot = firstItem.Select(x => x.zo_tot).First()
};
Debug.WriteLine("Entity: " + Entity);
var plainValues = resultDictionary.Values.SelectMany(x => x).ToList();
var resultSchedule = plainValues.Select(x => new medewerker_melding
{
medewerkerID = x.medewerkerID,
meldingID = x.meldingID,
datum_van = x.datum_van,
datum_tot = x.datum_tot,
ID = x.MM_ID
}).ToList();
Entity.medewerker_melding = resultSchedule;
}
You need to check whether MedewerkerMeldingContext dbC = new MedewerkerMeldingContext(); is implementing IEnumerable<T> else, you will not be able to preform the desired action on the table.
This kind of error (Could not find an implementation of the query
pattern) usually occurs when:
You are missing LINQ namespace usage (using System.Linq)
Typeyou are querying does not implement IEnumerable<T>
What i'd recommend, first check the namespace.
Second check for the IEnumerable<T> implementation.
Your query is good enough, you take the context and perform the linq, no issue here. It is 90% that you forgot the namespace since context is already implementing the IEnumerable<T> interface.

How to use LINQ to assign while selecting to new object

I have a data contract called GameImage and GameTone. I am trying to join the two entities, and assign a unique random position between 0-11 to an Image/Tone association. I am able to join the tables but am unsure if there is a way to assign the position while creating the object in a LINQ lambda expression.
// Need random positions from 0-11 to to be associated to an image/tone
var positions = Enumerable.Range(0, 11).Shuffle().ToList();
// Associate image/tones
imageToneData = game.GameImages.Shuffle()
.Join(game.GameTones, gi => gi.GameId, gt => gt.GameId, (gi, gt) => new ImageToneData
{
Image = new ImageData()
{
ImageFileName = gi.Image.ImageFileName,
ImageId = gi.ImageId
},
Tone = new ToneData()
{
ToneFileName = gt.Tone.ToneFileName,
ToneId = gt.ToneId
},
Position = // What goes here?
});
These are my data contracts
[DataContract]
public class ImageToneData
{
[DataMember]
public ImageData Image { get; set; }
[DataMember]
public ToneData Tone { get; set; }
[DataMember]
public int Position { get; set; }
}
[DataContract]
public class ImageData
{
[DataMember]
public int ImageId { get; set; }
[DataMember]
public string ImageFileName { get; set; }
}
}
[DataContract]
public class ToneData
{
[DataMember]
public int ToneId { get; set; }
[DataMember]
public string ToneFileName { get; set; }
}
var positions = Enumerable.Range(0, 11).OrderBy(a => Guid.NewGuid()).ToList();
// Associate image/tones
imageToneData = game.GameImages.Shuffle()
.Join(game.GameTones, gi => gi.GameId, gt => gt.GameId, (gi, gt) => new ImageToneData
{
Image = new ImageData()
{
ImageFileName = gi.Image.ImageFileName,
ImageId = gi.ImageId
},
Tone = new ToneData()
{
ToneFileName = gt.Tone.ToneFileName,
ToneId = gt.ToneId
},
Position = positions.First()
});

How to map nested Property with Automapper

I am trying to map Student with StudentDto, this is what I am doing but it is complaining about the nested property which is of type List<StudentContact>
Both the objects, StudentDto and Student have exactly the same properties, this is what i am using to try to map the objects.
var config = new MapperConfiguration(
cfg => cfg.CreateMap<StudentDto, Student>());
var mapper = config.CreateMapper();
var driverActivationResponse = mapper.Map <List<Student> > (studentDto);// "studentDto" is List<StudentDto>
my classes
public class StudentDto
{
public StudentDto()
{
if(StudentContacts==null) StudentContacts=new List<StudentContact>();
}
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
}
public class Student
{
public Student()
{
if(StudentContacts==null) StudentContacts=new List<StudentContact>();
}
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
}
public class StudentContact
{
public string ContactName { get; set; }
public string PrimaryContactNo { get; set; }
}
This should help -
AutoMapper.Mapper.CreateMap<Student, StudentDto>()
.ForMember(a => a.StudentContacts, b => b.ResolveUsing(c => c.StudentContacts));
var map = Mapper.Map<StudentDto>(new Student
{
Id = "100",
StudentContacts = new List<StudentContact>
{
new StudentContact{ContactName = "test",PrimaryContactNo = "tset"}
}
});
you cannot map like mapper.Map <List<Student>>(studentDto);. The top level member cannot be a list when using automapper.
Does it help to specify the source collection type and destination collection type in your Map call?
var driverActivationResponse = mapper.Map<List<Student>, List<StudentDto>>(studentDto);
It looks like the AutoMapper code you have is correct. If you're still getting an error, something else must be wrong. Perhaps your studentDto is not really a List<StudentDto>?
In any case, here's an entire example that works without error:
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
namespace ConsoleSandbox
{
class Program
{
public static void Main()
{
var config = new MapperConfiguration(
cfg => cfg.CreateMap<StudentDto, Student>());
var mapper = config.CreateMapper();
var studentDtos = new[]
{
new StudentDto
{
Id = "1",
StudentContacts = new[]
{
new StudentContact { ContactName = "Dan", PrimaryContactNo = "123" },
new StudentContact { ContactName = "Stan", PrimaryContactNo = "456" },
}.ToList()
},
new StudentDto
{
Id = "2",
StudentContacts = new[]
{
new StudentContact { ContactName = "Foo", PrimaryContactNo = "789" },
new StudentContact { ContactName = "Bar", PrimaryContactNo = "101112" },
}.ToList()
},
}.ToList();
var driverActivationResponse = mapper.Map<List<Student>>(studentDtos);
Console.WriteLine($"Contacts Count: {driverActivationResponse.Count}");
Console.ReadKey();
}
}
public class StudentDto
{
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
public StudentDto()
{
if (StudentContacts == null) StudentContacts = new List<StudentContact>();
}
}
public class Student
{
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
public Student()
{
if (StudentContacts == null) StudentContacts = new List<StudentContact>();
}
}
public class StudentContact
{
public string ContactName { get; set; }
public string PrimaryContactNo { get; set; }
}
}

Categories

Resources