【发布时间】:2016-06-17 07:07:12
【问题描述】:
由于 Entity Framework 7 尚不支持多对多关系,
我正在关注这个link 的工作。
这是上面链接中的代码:
class MyContext : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId);
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
问题
如何将Tag 与Post 关联?
换句话说,我怎样才能在联结表中添加一行?
【问题讨论】:
-
你尝试过类似
MyPost.PostTags.Add(new PostTag(){ ... })的方法吗?
标签: ef-code-first many-to-many relational-database entity-framework-core