我有一个我无法解决的问题。我想将用户创建的卡片组传输到我的API,但问题是卡和卡片组是数据库中的两个不同实体,这就是为什么我需要将卡片组和列表卡的信息传递给API的原因将它们添加到我的数据库。
我的实体:
public class Card
{
public Card() {
this.Decks = new HashSet<Deck>();
}
public int Id { get; set; }
[Column(TypeName = "json")]
public string Content { get; set; }
[NotMapped]
public virtual ICollection<Deck> Decks { get; set; }
}
public class Deck
{
public Deck() {
this.Cards = new HashSet<Card>();
}
public int Id { get; set; }
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime CreateAt { get; set; }
public User User { get; set; }
[NotMapped]
public virtual ICollection<Card> Cards { get; set; }
}
public class Join
{
public int DeckId { get; set; }
public Deck Deck { get; set; }
public int CardId { get; set; }
public Card Card { get; set; }
}
我的API:
[HttpPost]
public void Add ([FromBody] JsonObject request) {
}
JSON:
{
"Deck":{
"Name": "",
"CreateAt": "2007-07-15",
"User": "null"
},
"Crads":[
{"content": {}},
{"content": {}}
]
}
响应:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|99e854f-4f63859a690203b6.",
"errors": {
"$.Deck.User": [
"The JSON value could not be converted to MTG_Deck.Models.User. Path: $.Deck.User | LineNumber: 4 | BytePositionInLine: 22."
]
}
}
我认为最好在您的API中收到一个DTO,该DTO封装了您需要的两个类(Deck和Card)。然后在方法内部获取所需的信息,并将实体正确保存在数据库中。
public class AddDeckAndCardDTO
{
public Deck Deck { get; set; }
public List<Card> Card { get; set; }
}
并在API中添加方法
[HttpPost]
public void Add ([FromBody] AddDeckAndCardDTO request)
{
var card = request.Card;
var deck = request.Deck
// the code to mapped entities
// the code to save your entities
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句