1

我使用 MVC 4 和 EF Code First 5,我对 post 和 tag 实体有一个多对多的关系,

public class Post : BaseEntity
{

    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public virtual ICollection<PostTag> Tags { get; set; }
}



public class PostTag : BaseEntity
{
    public int TagId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

在 post 实体中使用这个 Fluent 映射:

    HasMany(p => p.Tags)
        .WithMany(t => t.Posts)
        .Map(pt => pt.ToTable("PostTagsJunction")
            .MapLeftKey("PostId")
            .MapRightKey("TagId"));

我添加新帖子的帖子服务:

public void Add(Post entity)
{
    _posts.Add(entity);
}

我的问题是:当我添加带有此标签的新帖子实体时:[“A”,“B”,“C”]

在数据库中存在这个标签:[“B”,“H”,“E”],

但是在标签实体中插入新的[“B”]记录,这是重复的!

我必须如何插入只插入 ["A","C"] 标签的新帖子?

我想变成这个(新帖子ID是3):

帖子:

postid
1
2
3

标签:

tagid   name
1       B
2       H
3       E
4       A
5       C

PostTagsJunction:

postid   tagid
1        2
1        3
2        3
2        1
3        1
3        4
3        5
4

0 回答 0