首页 > 解决方案 > 如何将 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."
        ]
    }
}

标签: asp.netentity-framework

解决方案


我认为最好在您的 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
 }

推荐阅读