Adding a model with join to another model for many to many without navigation property [duplicate]

喜你入骨 提交于 2019-12-12 01:16:15

问题


How can I insert a model Tag that belongs to a model Post when I have the models setup like this:

Post

public class Post
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
    public Post()
    {
       Tags = new List<Tag>();
    }
}

Tag

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
}

This question suggests to create a Post object then add Tags to the Tags collection, I couldn't get it working: Insert/Update Many to Many Entity Framework . How do I do it?

I want to add Tag to Post already in the database, how can I do that with EF. I'm new to EF.

This is what I've tried, if I send this to the API it doesn't insert any records and I can see that the new tag Id = 0 which doesn't exist in the database, but I'd think that'd cause a foreign key constraint error, not sure If I need to do something to auto generate Id for the tag:

{
    Name: "test"
}

API

[ResponseType(typeof(Tag))]
public IHttpActionResult PostTag(Tag tag)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var post = new Post();
    var tags = new List<Tag>();
    tags.Add(tag);

    post.Tags.Add(tag);
    post.Id = 10;
    db.Entry(post).State = EntityState.Modified;
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = tag.Id }, tag);
}

回答1:


I fetch the Post first add then save changes.

[ResponseType(typeof(Tag))]
public IHttpActionResult PostTag(TagDTO tagDTO)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var post = db.Posts.Find(TagDTO.PostId);
    post.Tags.Add(new Tag() { Name = tagDTO.Name });            
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = post.Tags.First().Id }, post);
}


来源:https://stackoverflow.com/questions/53977359/adding-a-model-with-join-to-another-model-for-many-to-many-without-navigation-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!