gpt4 book ai didi

c# - 如何为帖子添加标签?

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:39 25 4
gpt4 key购买 nike

所以我有一个 Post 和 Tag 类,它们应该是多对多的。但是我无法显示任何标签。

课后

public class Post
{
public Post()
{
this.Tags = new List<Tag>();
}

public int PostID { get; set; }
public string Title { get; set; }
public DateTime DateTime { get; set; }
public string Body { get; set; }

public virtual IList<Tag> Tags { get; set; }

}

标签类:

public class Tag
{
public int TagID { get; set; }
public string Name { get; set; }

public virtual ICollection<Post> Posts { get; set; }
}

还有我的 Controller 的一部分

[HttpPost]
public ActionResult Create([Bind(Include = "Title,Body,Tags")] BlogInputModel input)
{
if (ModelState.IsValid)
{

Post post = new Post
{
Title = input.Title,
Body = input.Body,
DateTime = DateTime.Now
};
post.Tags.Clear();
foreach (string tag in input.Tags.Split(' '))
{
post.Tags.Add(GetTag(tag));
}

db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Details", new { id = post.PostID });
}
return RedirectToAction("Index");
}

public ActionResult Details(int id)
{
var post = db.Posts.Where(x => x.PostID == id).First();
return View(post);
}

private Tag GetTag(string tagName)
{
return db.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag { Name = tagName };
}

这是我的上下文类

public class BlogContext : DbContext
{
public BlogContext() : base("BlogContext")
{
}

public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasMany(t => t.Tags)
.WithMany(p => p.Posts)
.Map(m => m.MapLeftKey("PostID")
.MapRightKey("TagID")
.ToTable("PostTags"));
}
}

我尝试修复它时遇到异常,但没有任何效果。 EF 不应该只创建 PostTags 表并且一切都应该连接吗?

或者我是否必须摆脱 modelBuilder 代码并创建我自己的第三个表,但如果是这样,我如何将帖子的 ID 传递给标签?

最佳答案

Shouldn't EF just create the PostTags table and everything should connect?

Or do I have to get rid of the modelBuilder code and create my own third table, but if so, how can I pass the ID of a post to the tags?

EF 足够聪明,知道需要一个新表来链接 TagPost因为你创造了:

  • IList<Tag>Post
  • ICollection<Post>Tag .

然后你可以删除你在OnModelCreating中写的代码EF 将创建一个新表来链接 TagPost .

删除 OnModelCreating 中代码的缺点是:

  • 您事先不知道 EF 将如何命名您的表 PostTagsTagPosts .想象一下,您需要创建一个与链接表相关的 SQL View ,知道表的名称会很酷。
  • 您不知道组合键在创建时的顺序是什么,因为您在使用 DbSet.Find 时需要使用相同的顺序。方法。此方法需要键的顺序与它们在链接表上的创建顺序相同。

关于c# - 如何为帖子添加标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com