将自连接映射到代码第一实体框架中的集合4.3 [英] Mapping a self-join to a collection in code first entity framework 4.3

查看:100
本文介绍了将自连接映射到代码第一实体框架中的集合4.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POCO类,映射到一个自定义的表,定义如下:

I have a POCO class that maps to a self-joined table defined like this:

CREATE TABLE [dbo].[GalleryCategories](
    [CategoryID] [int] IDENTITY(0,1) NOT NULL PRIMARY KEY CLUSTERED,
    [Name] [nvarchar](256) NOT NULL,
    [ParentID] [int] NULL REFERENCES [dbo].[GalleryCategories] ([CategoryID]) ON DELETE NO ACTION ON UPDATE NO ACTION, 
)

我知道有一种方法来定义一个关系,使用模型构建器来引用一个孩子的父母...(例如像这样

I know there's a way to define a relationship using the model builder to reference a parent from a child... (e.g. like this)

但是类I '试图映射这样...

But the class I'm trying to map looks like this...

public class GalleryCategory
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int? ParentID { get; set; }
    public List<Category> Subcategories { get; set; }
}

换句话说,我试图让所有子类别孩子们 - 即遍历层次结构,而不是层次结构。

In other words, I'm trying to get Subcategories populated with all of the children - i.e. traverse down the hierarchy, not up the hierarchy.

有没有办法使用EF?这必须是一个常见问题,但是我在谷歌搜索一小时后找不到: - )

Is there any way to do this using EF? This must be a FAQ somewhere but I couldn't find it after googling for an hour :-)

推荐答案

列出课堂中的子类别?如果是这样,它是一个自引用表,您可以创建映射,如下所示的数据注释:

Should that be a List Subcategories in your class? If so, and it's a self referencing table, you can create the mapping either way Data Annotations like this:

 public class GalleryCategory
    {
        [Key]
        public int CategoryID { get; set; }
        public string Name { get; set; }
        public int? ParentID { get; set; }
        [ForeignKey("ParentID")]
        public virtual List<GalleryCategory> Subcategories { get; set; }
    }

或以流利的方式:

 public class Model : DbContext
    {
        public DbSet<GalleryCategory> Categories { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<GalleryCategory>()
               .HasMany(x => x.Subcategories)
                .WithOptional()
                .HasForeignKey(g => g.ParentID);
        }
    }

这篇关于将自连接映射到代码第一实体框架中的集合4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆