实体框架代码优先 - 单个类的多对多
我有一个导航菜单提供程序,我正在尝试使用 MenuItem 对象将其移至 EF Code First(EF4、CPT5)。与其他任何事情相比,这更多的是一种适应与 EF Code First 建立不同关系的练习。
我的 MenuItem 有一个名为 SubMenuItems 的字段,它是 MenuItem 的集合。当我使用 EF Code First(不修改类)时,为 MenuItems 创建的表会为父菜单项添加一列。菜单将正确显示,但这消除了菜单项出现在多个子菜单中的任何能力。告诉 EF Code First 我希望每个 MenuItem 成为独立项并创建另一个将菜单项的 SubMenuItems 链接到其他 MenuItems 的表的正确方法是什么?
public class MenuItem
{
public int ID { get; set; }
public virtual SubMenuItems { get; set; }
public string Text { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public bool IsRoot { get; set; }
public bool RequiresAuthentication { get; set; }
public virtual ICollection<MenuPermission> RequiredPermissions { get; set; }
public bool HiddenIfAuthenticated { get; set; }
public int DisplayOrder { get; set; }
}
...
public class MyDbContext : DbContext
{
public DbSet<MenuItems> MenuItems { get; set; }
public DbSet<MenuItemPermission> MenuItemPermissions { get; set; }
...
}
我尝试过重写 OnModelCreating,但每次尝试都以要么被破坏,要么做与我不接触 OnModelCreating 时所做的完全相同的事情而告终。我确信我只是“做错了”。
谢谢!
I have a navigation menu provider that I am trying to move over to EF Code First (EF4, CPT5) using a MenuItem object. This is more of an exercise to get comfortable with building different relationships with EF Code First than anything else.
My MenuItem has a field called SubMenuItems that is a collection of MenuItems. When I use EF Code First (without modifying the classes) the table that is created for the MenuItems adds a column for the parent menu item. The menu will display properly, but this removes any ability to have a menu item appear in more than one sub menu. What is the proper way to tell EF Code First that I want each MenuItem to be a standalone item and to create another table that links a menu item's SubMenuItems to other MenuItems?
public class MenuItem
{
public int ID { get; set; }
public virtual SubMenuItems { get; set; }
public string Text { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public bool IsRoot { get; set; }
public bool RequiresAuthentication { get; set; }
public virtual ICollection<MenuPermission> RequiredPermissions { get; set; }
public bool HiddenIfAuthenticated { get; set; }
public int DisplayOrder { get; set; }
}
...
public class MyDbContext : DbContext
{
public DbSet<MenuItems> MenuItems { get; set; }
public DbSet<MenuItemPermission> MenuItemPermissions { get; set; }
...
}
I have attempted to override OnModelCreating but each attempt ended in either being broken or doing the exact same thing that it does without me touching OnModelCreating. I'm sure I'm just "doing it wrong."
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要为
MenuItem
实体设置多对多自引用关联,以便每个 MenuItem 可以有多个父项:You need to setup a Many-to-Many Self Referencing Association for
MenuItem
entity so that each MenuItem could have multiple Parent Items: