Entity Framework Code First 自身关联情况下的泛型递归实现

本文介绍了如何在Entity Framework Code First中,使用递归和泛型方法来处理自身关联的数据加载。通过反射和泛型,实现了一个通用的解决方案,能够将父子项递归地加载到一个list中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中所使用:使用EF可以将父子项全部加载进来,所以只是用递归将父子项放入list,反射加泛型使其通用。

一,实体:

public class Sys_city
    {
        public Sys_city()
        {
            children = new List<Sys_city>(); 
        }
        public int Id { get; set; }
        [StringLength(100)]
        public string title { get; set; }
        [StringLength(20)]
        public string zip_Code { get; set; }
        public int? ParentId { get; set; }
        public int level { get; set; }
        public int sort { get; set; }
        [StringLength(300)]
        public string CityFullName { get; set; }
        public string parent_s { get; set; }
        public virtual Sys_city Sys_City { get; set; }
        [ForeignKey("ParentId")] 
        public virtual ICollection<Sys_city> children { get; set; }
    }

二,数据表:

三,泛型实现:

public class Recursion
    {
        public IEnumerable<T> GetChildren<T>(ICollection<T> children, string propertyName)
        {
            if (children.Count() > 0)
            {
                return children.Concat(children.SelectMany(t => GetChildren(t.GetType().GetProperty(propertyName).GetValue(t) as ICollection<T>, propertyName)));
            }
            else
            {
                return children.ToList();
            }
        }

        public T GetFather<T>(T single, string propertyName, ref List<T> list) where T : class
        {
            if (single.GetType().GetProperty(propertyName).GetValue(single) != null)
            {
                list.Add(GetFather(single.GetType().GetProperty(propertyName).GetValue(single) as T, propertyName, ref list));
                return single;
            }
            else
            {
                return single;
            }
        }

四,使用方法:

            var single = 这里根据ID查询出单条记录
            Recursion rn = new Recursion();
            //这步操作取出所有子项,但不包含自身
            var children = rn.GetChildren(single.children, "children").ToList();
            //这步将自身加入
            children.Insert(0, single);
            
            List<Sys_city> Ecity = new List<Sys_city>();
            //这步操作取出所有父项,但不包含自身
            var e = rn.GetFather(single, "Sys_City", ref Ecity);
            //这步将自身加入
            Ecity.Add(e);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值