我有 2 个服务模型和 2 个 DAL 模型。在创建新作者时,我想将其书籍保存到 Book 表中。因此,我将有效负载作为 json 发送。但是,如果我尝试使模型适应 Book 模型,它的值为 null。所以我可以解决这个问题。我也试过model.Adapt<IEnumerable<Book>>()
了,这也为空。
public async Task<AuthorRequest> CreateAsync(AuthorRequest model)
{
var authorEntity= model.Adapt<Author>(); // works fine
var bookEntity =model.Adapt<Book>();//null
}
服务模型
public class AuthorRequest :Identifiable<string>
{
public string override Id{get;set;}
[Attr("name")]
public string Name { get; set; }
[Attr("surname")]
public string Surname { get; set; }
public ICollection<BookRequest> Books{get; set; }
}
public class BookRequest :Identifiable<string>
{
public string override Id{get;set;}
public string Title { get; set; }
}
DAL模型
public class Author : AuditableEntity
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("surname")]
public string Surname { get; set; }
[JsonProperty("books")]
public Relationship<IList<Book>> Books;
}
public class Book :AuditableEntity
{
[JsonProperty("Title")]
public string Title { get; set; }
[JsonProperty("Author")]
public Relationship<IList<Author>> Author;
}
使用 mapster 进行映射
TypeAdapterConfig<DAL.Models.Author, Service.Models.AuthorRequest>.NewConfig();
TypeAdapterConfig<DAL.Models.Book, Service.Models.AuthorRequest>.NewConfig();
TypeAdapterConfig<DAL.Models.Book, Service.Models.BookRequest>.NewConfig();
TypeAdapterConfig<Service.Models.AuthorRequest, DAL.Models.Author>.NewConfig();
TypeAdapterConfig<Service.Models.AuthorRequest, DAL.Models.Book>.NewConfig();
TypeAdapterConfig<Service.Models.BookRequest, DAL.Models.Book>.NewConfig();
AuthorRequest.JSON
{
"name": "William",
"surname": "Shakespeare",
"books": [{
"title": "Macheth"
}]
}