I have three entity.
public class Book
{
public string Name {get;set;}
}
public class Author
{
public string AuthorName {get;set;}
}
public class BookDTO
{
public string Name {get;set;}
public string AuthorName {get;set;}
}
how to map Book and Author to BookDTO ?
and how to map BookDTO to Book and Author?
I used the automapper in my solution.
You could create a mapping for each:
Mapper.CreateMap<Book, BookDTO>();
Mapper.CreateMap<Author, BookDTO>();
And then use it like this:
Book b = new Book { Name = "Gulliver's Travels" };
Author a = new Author { AuthorName = "Jonathan Swift" };
var dto = Mapper.Map<Book, BookDTO>(b);
Mapper.Map<Author, BookDTO>(a, dto);
Related
I would like to use automapper to map nested enumerable properties in existing enumerable nested properties.
Here is the problem simplify, i have Entities objects, they implement IEntity Interface, and Models objects, they implment IModel interfaces.
I would like to update easily and in a smart way IEntity object with IModel object
Example :
public class PersonEntity : IEntity
{
public int Id { get; set; }
public string Name { get; set }
public IEnumerable<AddressEntity> Addresses { get; set }
}
public class AddressEntity : IEntity
{
public int Id { get; set; }
public string Street { get; set }
public string entityField { get; set }
}
public class PersonModel : IModel
{
public int Id { get; set; }
public string Name { get; set }
public IEnumerable<AddressModel> Addresses { get; set }
}
public class AddressModel : IModel
{
public int Id { get; set; }
public string Street { get; set }
}
If i have these two instance og PersonEntity and AddressEntity :
var personModel = new PersonModel()
{
Id = 1,
Name = "Name",
Addresses = new List<AddressModel>() {
new AdressModel() { Id = 1, Street = "Street B" }
}
var person = new PersonEntity()
{
Id = 1,
Name = "Name",
Addresses = new List<AddressEntity>() {
new AdressEntity() { Id = 1, Street = "StreetA", EntityField ="entityValue" }
}
How can i map by Id, the Addresses element, to only erase the StreetA value by StreetB value, and keep existing entityField value intact ?
Thank you for help !
I'm trying to serialize a custom class with YamlDotNet library.
Here is my class:
public class Person
{
string firstName;
string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
And here is how I tried to serialize it:
StreamWriter streamWriter = new StreamWriter("Test.txt");
Person person = new Person("toto", "titi");
Serializer serializer = new Serializer();
serializer.Serialize(streamWriter, person);
But in my output file, I only have this : { }
What did I forget to do to serialize my class?
The default behavior of YamlDotNet is to serialize public properties and to ignore fields. The easiest fix is to replace the public fields with automatic properties:
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Person(string first, string last)
{
FirstName = first;
LastName = last;
}
}
You could alter the behavior of YamlDotNet to serialize private fields relatively easily, but I do not recommend that.
I have to create a Mapping with automapper.
Public class Source
{
public string Id;
public string Firstname;
public string Lastname;
}
Destination is
Public class Destination
{
public string Id;
public Person[] persons;
}
Person Class is
Public class Person
{
public string FirstName;
public string LastName;
}
I am trying to create mapping
AutoMapper.Mapper.CreateMap<Source, Destination>();
but I don't know how to map Firstname, Lastname to array of object Person.
AutoMapper.Mapper.CreateMap<Source, Destination>().AfterMap((s,d) => d.Person = new Person[] { FirstName = s.FirstName, LastName = s.LastName }));
This solution should create a new instance of Person however would you not be better off mapping them to a new class rather than an array?
I solved it .
AutoMapper.Mapper.CreateMap<Source, Destination>()
.AfterMap((s, d) => d.persons= new Person[1])
.AfterMap((s, d) => d.persons[0] = new Person{ FirstName= s.FirstName, LastName= s.LastName, RemoteId = s.Name
;
I am new to this concept of reflection and finding problem in retrieving property value from a string. E.g.
I have a class Employee with following properties :
public string Name {get;set;}
public int Age {get;set;}
public string EmployeeID {get;set;}
string s = "Name=ABCD;Age=25;EmployeeID=A12";
I want to retrieve the value of each property from this string and create a new object of Employee with those values retrieved from the string for each field.
Can anyone please suggest how it can be done using reflection ??
//may be..
string s = "Name=ABCD;Age=25;EmployeeID=A12";
string[] words = s.Split(';');
foreach (string word in words)
{
string[] data = word.Split('=');
string _data = data[1];
Console.WriteLine(Name);
}
Here an example of how you maybe could do it
it used Reflection like you wanted ^^
using System;
using System.Collections.Generic;
using System.Reflection;
namespace replace
{
public class Program
{
private static void Main(string[] args)
{
var s = "Name=ABCD;Age=25;EmployeeID=A12";
var list = s.Split(';');
var dic = new Dictionary<string, object>();
foreach (var item in list)
{
var probVal = item.Split('=');
dic.Add(probVal[0], probVal[1]);
}
var obj = new MyClass();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(dic[property.Name]);
if (property.PropertyType == typeof(Int32))
property.SetValue(obj, Convert.ToInt32(dic[property.Name]));
//else if (property.PropertyType== typeof(yourtype))
// property.SetValue(obj, (yourtype)dic[property.Name]);
else
property.SetValue(obj, dic[property.Name]);
}
Console.WriteLine("------------");
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Age);
Console.WriteLine(obj.EmployeeID);
Console.Read();
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
public string EmployeeID { get; set; }
}
}
I have a domain object
public class ProductModel
{
public long Id {get;set;}
public string Name {get;set;}
public string SerialNumber {get;set;}
}
Single Dto class:
public class ProductDto
{
public long Id {get;set;}
public string Name {get;set;}
public string SerialNumber {get;set;}
}
Single Dto class that is a list of Dto object:
public class ProductListDto : List<ProductDto>
{
public List<ProductDto> Products;
public ProductListDto()
{
Products = new List<ProductDto>();
}
}
And I'd like to map a list of domain objects to list of Dto objects such that the "Products" property of ProductListDto object AUTOMATICALLY is mapped with a list of ProductModel objects:
ProductListDto dto = new ProductListDto();
Mapper.CreateMap<ProductModel, ProductDto>();
/* dto = (ProductListDto) Mapper.Map<List<ProductModel>, List<ProductDto>>((List<ProductModel>)model); this code line causes error. It is commented out. */
dto.Products = Mapper.Map<List<ProductModel>, List<ProductDto>>((List<ProductModel>)model); // (*) works OK but need to specify "Products" property
The code line (*) works OK, but I'd like to know if there is another way to AUTOMATICALLY (implicitly) map that "Products" property of dto object other than the code line (*)?
That means I do not have to write code like the left hand side of code line (*).
You will need to create a mapping for it. Something like this should work:
namespace StackOverflow
{
using System.Collections.Generic;
using AutoMapper;
public class MyProfile : Profile
{
public override string ProfileName
{
get
{
return "MyProfile";
}
}
protected override void Configure()
{
Mapper.CreateMap<ProductModel, ProductDto>();
Mapper.CreateMap<List<ProductModel>, ProductListDto>()
.ForMember(dest => dest.Products,
opt => opt.MapFrom(
src => Mapper.Map<List<ProductModel>,
List<ProductDto>>(src)));
}
}
}
Then in your code you can do:
dto = Mapper.Map<List<ProductModel>, ProductListDto>((List<ProductModel>)model);
Here are a couple of unit tests to show how it works:
namespace StackOverflow
{
using System.Collections.Generic;
using AutoMapper;
using NUnit.Framework;
[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
}
[Test]
public void AutoMapper_DriverMapping_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
var products = new List<ProductModel>
{
new ProductModel
{
Id = 1,
Name = "StackOverflow Rocks",
SerialNumber = "1234"
},
new ProductModel
{
Id = 2,
Name = "I Also Rock",
SerialNumber = "4321"
}
};
var productsDto =
Mapper.Map<List<ProductModel>, ProductListDto>(products);
Assert.That(productsDto, Is.Not.Null);
Assert.That(productsDto.Products, Is.Not.Null);
Assert.That(productsDto.Products.Count, Is.EqualTo(2));
}
}
}