将具有联接的模型添加到许多没有导航属性的模型中 [英] Adding a model with join to another model for many to many without navigation property

查看:66
本文介绍了将具有联接的模型添加到许多没有导航属性的模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我具有如下模型设置时,如何插入属于模型Post的模型Tag:

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

发布

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>();
    }
}

标记

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

此问题建议创建一个Post对象,然后将Tags添加到Tags集合中,但我无法使其正常工作: 插入/更新多对多实体框架.我该怎么办?

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?

我想在数据库中已经将Tag添加到Post,如何使用EF做到这一点.我是EF的新手.

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

这是我尝试过的方法,如果将其发送到API,它不会插入任何记录,并且我可以看到数据库中不存在的新tag Id = 0,但是我认为会导致外键约束错误,不确定是否需要为标签自动生成ID:

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);
}

推荐答案

我先获取帖子,然后添加添加,然后保存更改.

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);
}

这篇关于将具有联接的模型添加到许多没有导航属性的模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆