asp.net - 如何将 2 个对象发送到我的 API (ASP.NET)?
问题描述
我有一个我无法解决的问题。我想将用户创建的卡片组传输到我的 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 中收到一个封装了您需要的两个类(Deck 和 Card)的 DTO。然后在您的方法中获取您需要的信息并将实体正确保存在数据库中。
public class AddDeckAndCardDTO
{
public Deck Deck { get; set; }
public List<Card> Card { get; set; }
}
以及 API 中的 Add 方法
[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
}
推荐阅读
- c# - 在 .NET Framework 4.5 中使用雪花
- html - 在相同的块上,但有间距
- postgresql - 如何使用 psycopg2 客户端从选择查询中获取 col 标头?
- python - 如何匹配来自具有不同大小的两个数据框的多个列?
- shell - 在 shell UNIX 上恢复已终止的作业
- html - 如何自动创建表?使用 html+angular+typescript
- ios - 是否有人为 SCNAnimation Player 使用了 animationDidStop 或 animationDidStart ?
- ios - 斯威夫特用户界面。NavigationView 嵌套按钮
- optaplanner - Optaplanner,构建启发式阶段使用什么移动类型?
- python - 来自 codewars 的 ROT13 Python 3