tnblog
首页
视频
资源
登录

Abp 级联查询和级联删除

5905人阅读 2022/3/30 17:27 总访问:1092466 评论:0 收藏:0 手机
分类: ABP

Abp级联查询,主要要设置主子表的外键关系。

[Table("School")]
    public class School : Entity<int>
    {

        public string Name { get; set; }

        public virtual List<Student> Students { get; set; } 
    }

    [Table("Student")]
    public class Student : Entity<int>
    {
        [Required]
        public virtual School School { get; set; }

        public string Name { get; set; }
    }

例如School和Student实体。在子表Student的School属性上添加[Required]标识。这样我们生成的Migration文件,就会自动生成外键和级联删除的关系。

这种要注意,软删除时,不会触发级联删除。所以我们的Model不要继承ISoftDelete接口。

查询时,要注意使用GetAllIncluding方法。

public List<School> GetAllSchool()
        {           return _schoolRepository.GetAllIncluding(s=>s.Students).ToList();
        }

但是abp只提供了GetAll时的GetAllIncluding方法,通过Id查询单个对象时,没有。我们可以在仓储的实现中自己实现。

public class SchoolRepository : PHMESRepositoryBase<School>, ISchoolRepository
    {
        IDbContextProvider<PHMESDbContext> _dbContext;
        public SchoolRepository(IDbContextProvider<PHMESDbContext> dbContextProvider) : base(dbContextProvider)
        {
            _dbContext = dbContextProvider;
      
        }
 
        public List<School> GetAllSchool()
        {
           var list= _dbContext.GetDbContext().school.Include(p=>p.Students).ToList();

            return list;
        }

        public School GetSchool(int id)
        {
           return _dbContext.GetDbContext().school.Where(p => p.Id == id).Include(p=>p.Students).First() ;
        }
    }

级联删除,就直接通过Id删除主表,子表也会自动删除。

 public void DeleteSchool(int id)
        {            var a = _schoolRepository.Get(id);
            _schoolRepository.Delete(a);
        }


原文地址:https://www.cnblogs.com/czly/p/13267072.html

评价
没有个性,不需要签名
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术