【发布时间】:2017-06-06 13:22:55
【问题描述】:
我点击此链接enter link description here 创建多对多关系。但是,我不知道如何创建标签值并将其更新为 Post 对象。
任何帮助将不胜感激。
更新,相关代码
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; }
}
Update2:更新记录的代码 使用下面的代码,它将在三个表中创建记录。
var p = new Post { Content = "C1" };
var t = new Tag { TagId = "T1" };
var pt = new PostTag { Post = p, Tag = t };
_context.PostTag.Add(pt);
_context.SaveChanges();
但是,使用下面的代码,它将在中间表 PostTag 中插入新记录,而不是更新以前的记录。
var t1 = new Tag { TagId = "T3" };
var t2 = new Tag { TagId = "T4" };
var p =_context.Posts.Find(1);
p.PostTags = new List<PostTag>() {
new PostTag{ Post=p, Tag=t1},
new PostTag{ Post=p, Tag=t2}
};
_context.Posts.Update(p);
_context.SaveChanges();
【问题讨论】:
-
共享模型类的代码
-
这是链接中的代码,我已经更新了我的帖子。
-
代码运行良好。你期待的结果是什么?特别是您能否详细说明“而不是更新以前的记录”。您更新了哪些以前的记录?
标签: asp.net-core entity-framework-core