2.2、ABP多表查詢


1.創建實體

多表查詢,在ABP或者EF中都很簡單,這里我們創建一個Demo,一個學生實體、一個學校實體。學校里面可以有很多學生,學生有一個學校。 

實體如下:

學校

 1 public class School : Entity<long>
 2 {  3       public string Name { get; set; } 
 5 
 6       public string Address { get; set; }
 8 
 9       /// <summary>
10       /// 學校里面的學生們 11       /// </summary>
12       public List<Student> Students { get; set; } 13 }

 

學生

 1 public class Student : Entity<long>
 2 {  3 
 4    public string Name { get; set; }  5 
 6    /// <summary>
 7    /// 學生所在的學校  8    /// </summary>
 9    public School School { get; set; } 10 
11 }

 

2.創建數據

現在我們來創建一下Student與School的數據。

School的數據如下:

Student的數據如下:

可以看到,Student名字為alun1、alun2、alun3的對應School1、2、1。

 

3.查詢實體

下面,我們在應用層AppService下面用Repository來查詢結果如何。

 1   //用GetAllIncluding方法來查詢所有學生的信息,結果包含School實體
 2   var listStudent1 = _studentRepository.GetAllIncluding(s=>s.School).ToList();  3 
 4 
 5   //用GetAll方法來查詢所有學生的信息,結果包含School實體
 6   var listStudent2 = _studentRepository.GetAll().ToList();  7 
 8 
 9   //用GetAll方法來查詢所有學校的信息,結果包含List Students實體
10   var listSchool1 = _schoolRepository.GetAll().ToList(); 11 
12 
13   //用GetAllIncluding方法來查詢所有學校的信息,結果包含List Students實體
14   var listSchool2 = _schoolRepository.GetAllIncluding(s=>s.Students).ToList();
 
        

可以看到,結果都包含Student包含School的實體,而且School包含集合是Students。

值得注意的是,這里的GetAllIncluding與GetAll的區別是,GetAllIncluding是明確的指明我要查詢的實體里面包含的其他表的實體也要查詢出來。

例如,GetAllIncluding(s=>s.School),告訴EF,查詢Student的時候,請把它關聯的School也查詢出來。

如果有多個實體關聯,請用逗號“,”隔開。例如 GetAllIncluding(s=>s.School, s=>s.Class)

 

對於ABP,如果是多租戶,用戶等多租戶的信息查詢不到的情況下,在查詢前請加下面一句話

 //去掉多租戶查詢時的Filter 
CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant, AbpDataFilters.MustHaveTenant);

因為在做多租戶的查詢是,ABP默認會加一些Filter,只能查詢當前登錄用戶的信息,其他用戶的信息Filter掉。

所以上面的意思是去掉多租戶查詢時的Filter

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM