【问题标题】:assgning several tag for a blog post implementaion [closed]为博客文章实现分配多个标签[关闭]
【发布时间】:2013-08-12 13:28:24
【问题描述】:

我要让用户能够为博客帖子分配多个标签(就像 stackoverflow 对标签和问题所做的那样),这是我的帖子模型

 public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public string Summary { get; set; }
        public DateTime CreationDate { get; set; }
        public string UrlSlug { get; set; }
        public string Picture { get; set; }
        public int TagId { get; set; }
        public virtual Tag Tag { get; set; }
    }

这是标签

public class Tag
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreationDate { get; set; }
        public string TagSlug { get; set; }

    }

当我想创建一个帖子时,我只需在下拉列表中获取所有标签的列表,然后在帖子操作中获取它的 ID,等等等等!那么,为了可以为帖子分配多个标签,应该如何更改我的模型?

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework


    【解决方案1】:

    听起来您想与您的PostsTags 建立Many:Many 关系,因为Post 可以有许多Tags,而Tag 将应用于许多Posts .

    这意味着您至少要在您的Post 对象上存储相关Tags 的集合。或者,您可能还希望在您的 Tag 对象上存储关联的 Posts 集合。

    因此,将您的单曲 Tag 更改为收藏集:

    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public string Summary { get; set; }
        public DateTime CreationDate { get; set; }
        public string UrlSlug { get; set; }
        public string Picture { get; set; }
    
        // Navigation property
        public virtual ICollection<Tag> Tags { get; set; }
    }
    
    public class Tag
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreationDate { get; set; }
        public string TagSlug { get; set; }
    
        // Navigation property (optional)
        public virtual ICollection<Post> Posts { get; set; }
    }
    

    如果您进行代码优先开发,Entity Framework 应该能够使用默认约定/映射来整理您的数据库结构和表。

    如果您已经有一个现有的数据库,您可能需要执行一些显式映射,例如

     modelBuilder.Entity<Post>()
                    .HasMany(t => t.Tags)
                    .WithMany(p => p.Posts)
                    .Map(m => m.MapLeftKey("PostId")
                               .MapRightKey("TagId")
                               .ToTable("PostTags"));
    

    【讨论】:

    • 感谢您的回答,我已经发布了我的网站,现在想使用代码优先迁移,是否可以将您的解决方案与 EF 代码优先迁移一起使用??
    • 嗨,虽然我实际上没有使用过 Code First 迁移,但它看起来应该相当简单。 Entity Framework 文档中的 Code First 迁移部分有一些很好的教程:msdn.microsoft.com/en-us/data/ee712907(Code First 迁移大约在页面的一半处)。
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多