【问题标题】:From hard coded model to data driven menu从硬编码模型到数据驱动菜单
【发布时间】:2017-01-20 12:04:12
【问题描述】:

我正在尝试改变它 Tutorial 从表中读取数据。我通过添加 Id 键字段修改了 NavigationMenu.cs 模型:

public class NavigationMenu
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Text { get; set; }
    public string Action { get; set; }
    public string Controller { get; set; }
    public string Icon { get; set; }
    public bool Selected { get; set; }

    public List<NavigationMenu> MenuChildren;

}

添加了上下文:

public class NavigationMenuContext : DbContext
{

    public NavigationMenuContext() : base("name=DefaultConnection")  
    {
    }

    public DbSet<NavigationMenu> NavigationMenus { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }
}

并修改了具体的控制器:

public class NavigationController : Controller
{

    // GET: NewMenu
    public ActionResult Index()
    {
        NavigationMenuContext navigationMenuContext = new NavigationMenuContext();
        List<NavigationMenu> menuItems = navigationMenuContext.NavigationMenus.ToList();
        return View(menuItems);
    }       

    [ChildActionOnly]
    public ActionResult GenerateMenu()
    {

        NavigationMenuContext navigationMenuContext = new NavigationMenuContext();
        List<NavigationMenu> menuItems = navigationMenuContext.NavigationMenus.ToList();

        string action = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString() == "Index" ? "" : ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
        string controller = ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();

        foreach (var item in menuItems)
        {
            if (item.MenuChildren != null)
            {
                foreach (var cItem in item.MenuChildren)
                {
                    if (cItem.Controller == controller && cItem.Action == action)
                    {
                        cItem.Selected = true;
                        break;
                    }
                    else
                    {
                        cItem.Selected = false;
                    }
                }
            }
            if (item.Controller == controller && item.Action == action)
            {
                item.Selected = true;
                break;
            }
            else
            {
                item.Selected = false;
            }
        }

        return PartialView("~/Views/Shared/_Navigation.cshtml", menuItems);
    }

}

但我无法使用二级菜单获得相同的结果: NavigationMenus Table

如何修改代码以在视图中呈现二级菜单?

【问题讨论】:

  • 如何填充 MenuChildren 属性?在数据库表中,所有菜单项看起来都在同一级别?他们的亲子关系如何?您应该在表中有一个 parentMenuId 列,该列将指示谁是父菜单项。如果 parentMenuId 为 0 或 null 则可以将其视为顶级菜单。您还需要更改 EF 绑定以支持一对多关系。
  • 请查看我的回答,希望对您有所帮助

标签: c# asp.net-mvc entity-framework poco data-driven


【解决方案1】:
Hi this is the  way you can achive what you want to do . I just added a line on OnMidelCreating and then testted the code woith 

  var result = context.MaineMenu.ToList(); // here I gold child menus in the list 


public class NavigationMenuContext : DbContext
{

public NavigationMenuContext() : base("name=DefaultConnection")  
{
}

public DbSet<NavigationMenu> NavigationMenus { get; set; }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
    -- this is changed -- 
    modelBuilder.Entity<NavigationMenu>().HasMany(c => c.MenuChildren);
 }
}

--- 在此之后,当我添加一个新的迁移时,迁移看起来像这样。 请参阅新的 Id 列和外键已由 EF 添加。

public override void Up()
    {
        CreateTable(
            "dbo.NavigationMenus",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Text = c.String(),
                    Action = c.String(),
                    Controller = c.String(),
                    Icon = c.String(),
                    Selected = c.Boolean(nullable: false),
                    NavigationMenu_Id = c.Int(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.NavigationMenus", t => t.NavigationMenu_Id)
            .Index(t => t.NavigationMenu_Id);

    }

    public override void Down()
    {
        DropForeignKey("dbo.NavigationMenus", "NavigationMenu_Id", "dbo.NavigationMenus");
        DropIndex("dbo.NavigationMenus", new[] { "NavigationMenu_Id" });
        DropTable("dbo.NavigationMenus");
    }

SQL 服务器中的数据和应用程序的输出

类-----

    public class SampleDbContext : DbContext
    {
        public SampleDbContext()
            : base("name=SampleDBConnection")
        {
            this.Configuration.LazyLoadingEnabled = false;
        }



        public DbSet<NavigationMenu> MaineMenu { get; set; }



        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Candidate>().HasMany(t => t.SkillSets).WithMany(t => t.Candidates)
                .Map(m =>
                {
                    m.ToTable("candidate_skillset");
                    m.MapLeftKey("candidate_id");
                    m.MapRightKey("skillset_id");
                });

            modelBuilder.Entity<SkillSet>().ToTable("skillset");
            modelBuilder.Entity<Candidate>().ToTable("candidate");

            modelBuilder.Entity<NavigationMenu>().HasMany(c => c.MenuChildren);



        }
    }


    public class NavigationMenu
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public NavigationMenu()
        {
            MenuChildren = new Collection<NavigationMenu>();
        }

        public string Text { get; set; }
        public string Action { get; set; }
        public string Controller { get; set; }
        public string Icon { get; set; }
        public bool Selected { get; set; }


        public ICollection<NavigationMenu> MenuChildren { get; set; }

    }

【讨论】:

  • MenuChidren 属性如何从数据库初始化?查看用户共享的表结构,MenuChidren 不可能有任何项目。
  • 嗨@ChetanRanpariya,当我在modelbuilder中添加该行时,EF自动创建了一个ID,然后在表格上创建为foriegnkey,这样您就可以读取特定id的孩子。
  • @ChetanRanpariya 在此更改后添加了我的迁移看看。我将在控制台应用程序上添加表格数据和结果。
  • @ChetanRanpariya 使用数据和应用程序输出检查更新的答案。我希望你喜欢它。
  • @ChetanRanpariya 我们可以在主类中添加该外键,以便我们可以设置子菜单的父菜单。 EF 自动创建它,但我们可以选择在我们的 DBSet 类中声明它。我没有展示那部分,因为问题是关于如何创建模型和检索数据。
猜你喜欢
  • 1970-01-01
  • 2015-03-08
  • 2015-06-21
  • 2014-10-17
  • 1970-01-01
  • 2019-08-02
  • 2013-06-19
  • 1970-01-01
  • 2013-08-30
相关资源
最近更新 更多