[英]Mapping Database Entity to DTO Using Automapper
I am using AutoMapper. 我正在使用AutoMapper。 I am facing an issue regarding mapping my DTO to database entity.
我遇到有关将我的DTO映射到数据库实体的问题。 I want to update my existing data in the database by mapping my updated DTO to DB Entity using AutoMapper rather to manually map the DTO to DB Entity.
我想通过使用AutoMapper将更新的DTO映射到数据库实体来更新数据库中的现有数据,而不是手动将DTO映射到数据库实体。
First of all define your DTO related to the entity. 首先定义与实体相关的DTO。 For example
例如
public class Author {
public string Name { get; set; }
}
public class Book {
public string Title { get; set; }
public Author Author { get; set; }
}
public class BookDTO {
public string Title { get; set; }
public string Author { get; set; }
}
Then init your Automap somewhere in your application startup code: 然后在应用程序启动代码中的某处初始化Automap:
AutoMapper.Mapper.CreateMap<Book, BookDTO>()
.ForMember(dest => dest.Author,
opts => opts.MapFrom(src => src.Author.Name));
AutoMapper.Mapper.CreateMap<Book, BookDTO>().ReverseMap()
Now and example of an update method froma the DTO to the entity: 现在,从DTO到实体的更新方法示例:
public int Update(BookDTO dto) {
var entity = _context.Books.FindAsync(dto.id);
if (entity == null) throw new ItemNotFoundException(dto.id);
AutoMapper.Mapper.Map(dto, entity)
return _context.SaveChanges();
}
And another example for the insert: 插入的另一个示例:
public int Insert(BookDTO dto) {
var entity = AutoMapper.Mapper.Map<Book>(dto);
_context.Provinces.Add(entity);
return _context.SaveChanges();
}
More info on http://cpratt.co/using-automapper-getting-started/ 有关更多信息,请访问http://cpratt.co/using-automapper-getting-started/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.