Работа с библиотекой AutoMapper - C#
Формулировка задачи:
Помогите разобраться с AutoMapper'ом. Вот допустим есть 2 следующих класса в Entity Framework:
А мне нужно получить следующий класс:
Как это можно сделать? В гугле искал, но не понял как это сделать. Спасибо
public class User
{
public int ID {get; set;}
public string Name {get; set;}
public int Age {get; set;}
public int PositionId {get; set;}
}
public class Position
{
public int ID {get; set;}
public string Description {get; set;}
}public class UserUpdate
{
public int ID {get; set;}
public string Name {get; set;}
public int Age {get; set;}
public string Description {get; set;}
}
Понятно, что это можно сделать обычным Include и перебрать в новую коллекцию UserUpdate, но меня интересует другой способ
Решение задачи: «Работа с библиотекой AutoMapper»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoMapper;
using ConsoleApplication14.data;
using ConsoleApplication14.Mapping;
using AutoMapper.QueryableExtensions;
namespace ConsoleApplication14
{
class Program
{
static void Main()
{
AutoMapperConfig.Config();
if (File.Exists("MyDateBase.db"))
{
File.Delete("MyDateBase.db");
}
using (var db = new SqliteContext("MyDateBase.db"))
{
var position = new Position()
{
Description = "Best Programmer"
};
db.Positions.Add(position);
db.SaveChanges();
var user = new User()
{
Name = "Kos",
Age = 23,
PositionId = position.Id
};
db.Users.Add(user);
db.SaveChanges();
}
using (var db = new SqliteContext("MyDateBase.db"))
{
var userUpdates = db.Users.ProjectTo<UserUpdate>().ToList();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(string.Join(Environment.NewLine, userUpdates));
}
Console.ReadKey();
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int PositionId { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
public Position()
{
Users = new HashSet<User>();
}
public int Id { get; set; }
public string Description { get; set; }
public ICollection<User> Users { get; set; }
}
public class UserUpdate : IHaveCustomMappings
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Description { get; set; }
public void CreateMappings(IMapperConfiguration configuration) => configuration.CreateMap<User, UserUpdate>()
.ForMember(m => m.Description, opt => opt.MapFrom(u => u.Position.Description));
public override string ToString()
{
return $"Id: {Id}, Name: {Name}, Age: {Age}, Description: {Description}";
}
}
}