我已经有很多标签,我已经有很多帖子了。我只想发布2个Id并在我的多对多表中插入这两个Id,以便链接2条记录。
我正在使用Entity Framework和Fluent Api。
表1称为标签,表2称为帖子,表3称为TagsPosts
我的TagsPosts表有以下内容:
Tag_Id
Post_Id
我只想添加这两个ID的新记录,如下所示:
var entry = new TagPost()
{
Tag_Id = tagId,
Post_Id = postId
};
ApplicationDbContext.TagsPosts.Add(entry);
在我的背景下,我有:
public class ApplicationDbContext
{
public DbSet<Tag> Tags{ get; set; }
public DbSet<Post> Posts{ get; set; }
public DbSet<TagPost> TagsPosts { get; set; }
}
我流畅的API关系:
ToTable("Tags");
HasKey(t => t.Id);
HasMany(t => t.Posts).WithMany(p => p.Tags);
问题是当我尝试使用代码首先添加迁移时出现错误:
EntityType 'TagPost' has no key defined. Define the key for this EntityType.
TagsPosts: EntityType: EntitySet 'TagsPosts' is based on type 'TagPost' that has no keys defined.
这就是TagPost的样子:
public class TagPost
{
public int Tag_Id { get; set; }
public int Post_Id { get; set; }
}
我究竟做错了什么?
如果按惯例映射此M2M关系,则不必包含TagPost类。
modelBuilder.Entity<Tag>()
.ToTable("Tags")
.HasKey(t => t.Id)
.HasMany(t => t.Posts)
.WithMany(p => p.Tags)
.Map(cs =>
{
cs.MapLeftKey("Tag_Id");
cs.MapRightKey("Post_Id");
cs.ToTable("TagPost");
});
阅读本文以获取更多信息:http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
编辑:
//get post object from context
var post = context.Posts.Find(postId);
//get tag object from context
var tag = context.Tags.Find(tagId);
//associate objects
post.Tags.Add(tag);
//commit to db
context.SaveChanges();