【发布时间】:2018-10-11 11:23:22
【问题描述】:
我有 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
}
Service.Models
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.Model
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"
}]
}
【问题讨论】:
-
我不了解 Mapster,但您为什么希望
model.Adapt<Book>()在这里工作?如果model.Adapt<Author>()映射到作者,那么这很有效,因为模型看起来像一个Author对象。但它只包含(可能多本)书,它不是一本书,所以它不会映射也就不足为奇了。也许你需要在这里做model.Books.Adapt<Book[]>()之类的事情?
标签: c# asp.net-core json-api mapster