【发布时间】:2019-02-28 06:28:04
【问题描述】:
我已经有很多标签,我已经有很多帖子。我只想发布 2 个 ID 并将这 2 个 ID 插入到我的多对多表中,以便将 2 条记录链接起来。
我正在使用实体框架和 Fluent Api。
表 1 称为标签, 表 2 称为帖子, 表 3 称为 TagsPosts
我的 TagsPosts 表有以下内容:
Tag_Id
Post_Id
我只想用这 2 个 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; }
}
我的 fluent 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; }
}
我做错了什么?
【问题讨论】:
标签: entity-framework ef-fluent-api