防止多对多关系中的重复插入

时间:2013-02-04 18:30:48

标签: asp.net-mvc asp.net-mvc-4 ef-code-first

我使用MVC 4和EF Code First 5, 我对帖子和标签实体有多对多的关系,

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

0 个答案:

没有答案
相关问题