forked from dotnetzoom/AspNetCore-WebApi-Course
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBaseDto.cs
62 lines (51 loc) · 1.88 KB
/
BaseDto.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using AutoMapper;
using Entities;
using System.ComponentModel.DataAnnotations;
using WebFramework.CustomMapping;
namespace WebFramework.Api
{
public abstract class BaseDto<TDto, TEntity, TKey> : IHaveCustomMapping
where TDto : class, new()
where TEntity : class, IEntity<TKey>, new()
{
[Display(Name = "ردیف")]
public TKey Id { get; set; }
public TEntity ToEntity(IMapper mapper)
{
return mapper.Map<TEntity>(CastToDerivedClass(mapper, this));
}
public TEntity ToEntity(IMapper mapper, TEntity entity)
{
return mapper.Map(CastToDerivedClass(mapper, this), entity);
}
public static TDto FromEntity(IMapper mapper, TEntity model)
{
return mapper.Map<TDto>(model);
}
protected TDto CastToDerivedClass(IMapper mapper, BaseDto<TDto, TEntity, TKey> baseInstance)
{
return mapper.Map<TDto>(baseInstance);
}
public void CreateMappings(Profile profile)
{
var mappingExpression = profile.CreateMap<TDto, TEntity>();
var dtoType = typeof(TDto);
var entityType = typeof(TEntity);
//Ignore any property of source (like Post.Author) that dose not contains in destination
foreach (var property in entityType.GetProperties())
{
if (dtoType.GetProperty(property.Name) == null)
mappingExpression.ForMember(property.Name, opt => opt.Ignore());
}
CustomMappings(mappingExpression.ReverseMap());
}
public virtual void CustomMappings(IMappingExpression<TEntity, TDto> mapping)
{
}
}
public abstract class BaseDto<TDto, TEntity> : BaseDto<TDto, TEntity, int>
where TDto : class, new()
where TEntity : class, IEntity<int>, new()
{
}
}