Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

asp.net web api - How to use HttpPost in Entity Framework Core 5 Web API with a Many to Many Relations

I'm very new with EF Core 5 but the first thing I needed to do was TO post a new item/object which has child items (Many-to-many).

I have set up my models like this:

public class Post
{
    public int id { get; set; }
    public string name { get; set; }

    public ICollection<Tag> tags { get; set; }
}

public class Tag
{
    public int id { get; set; }
    public string name { get; set; }
    [JsonIgnore]
    public ICollection<Post> posts { get; set; }
}

...and the DbContext is very simple:

public DbSet<Post> posts { get; set; }
public DbSet<Tag> tags { get; set; } 

And the migrations work as expected, creating the join table automatically. But I can't figure out for the life of me how to post a new item:

This is the json ob posted by the client:

{
  "name": "New Post Name"
  "tags": [
    {
                    "id": 11
    },
    {
                    "id": 12
    },
    {
                    "id": 16
    },
    {
                    "id": 19
    }
  ]
}

The User will have entered a Name for the Post in a HTML form and selected a number of Tags available in a check box list.

....and in my controller:

[HttpPost]
public async Task<ActionResult<Post>> PostPost(Post post)
{ 
    // can anybody help and tell me what goes in here? Cheers
}

Thanks a lot in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...