【问题标题】:Connecting Id's in many to many table - Entity Framework在多对多表中连接 Id - 实体框架
【发布时间】: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


    【解决方案1】:

    如果按照惯例映射此 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();
    

    【讨论】:

    • 感谢您的帮助。看起来不错,但是如何在没有 TagPost 类的情况下将条目添加到数据库中?我需要将它包含在我的 DbContext 中吗?
    • 只需使用tag.Posts.Add(post) 并保存您的上下文。 EF 已经知道在幕后使用 TagPost 表。
    • 请原谅我的无知,但您能否根据我上面的内容提供一个存储库的示例?另外,我不是添加帖子,只是添加ID以将数据库中已经存在的2条记录链接在一起,不是吗?
    • @DBoi 我在答案中添加了一个示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多