Skip to content

Exclude field

shuxin edited this page Nov 20, 2023 · 5 revisions

排除字段

查询时排除指定的字段:

IQuery<Person> q = this.DbContext.Query<Person>();

//排除指定的字段
List<Person> persons = q.Exclude(a => a.Name).ToList();
/*
 * 生成的 sql 语句中不包含 Name 字段
 * SELECT [Person].[Gender],[Person].[Age],[Person].[CityId],[Person].[CreateTime],[Person].[EditTime],[Person].[Id]
   FROM [Person] AS [Person]
 */


//使用匿名类的方式排除多个字段
persons = q.Exclude(a => new { a.Name, a.Age, a.EditTime, a.CityId, a.CreateTime }).ToList();
/*
 * SELECT [Person].[Gender],[Person].[Id] FROM [Person] AS [Person]
 */


//使用 new object[] 形式排除多个字段
persons = q.Exclude(a => new object[] { a.Name, a.Age, a.EditTime, a.CityId, a.CreateTime }).ToList();
/*
 * SELECT [Person].[Gender],[Person].[Id] FROM [Person] AS [Person]
 */

在多表连接中使用:

var joinResults = q.LeftJoin<City>((person, city) => person.CityId == city.Id)
                   .Select((person, city) => new { Person = person, City = city })
                   .Exclude(a => new Object[] { a.Person.Name, a.City.Name })
                   .ToList();
/*
 * 生成的 sql 语句中不包含 Name 字段
 * SELECT [Person].[Gender],[Person].[Age],[Person].[CityId],[Person].[CreateTime],[Person].[EditTime],[Person].[Id]
   ,[City].[ProvinceId],[City].[Id] AS [Id0] 
   FROM [Person] AS [Person] 
   LEFT JOIN [City] AS [City] ON [Person].[CityId] = [City].[Id]
 */

在导航属性中使用:

var cities = this.DbContext.Query<City>().Exclude(a => a.Name)
      .IncludeMany(a => a.Persons).ExcludeField(a => a.Name)
      .Include(a => a.Province).ExcludeField(a => a.Name)
      .ToList();
/*
 * 生成的 sql 语句中不会包含 City.Name、Person.Name、Province.Name 3个字段
 * SELECT [City].[ProvinceId],[City].[Id]
   ,[Province].[Id] AS [Id0]
   ,[Person].[Gender],[Person].[Age],[Person].[CityId],[Person].[CreateTime],[Person].[EditTime],[Person].[Id] AS [Id1]
   FROM [City] AS [City] 
   INNER JOIN [Province] AS [Province] ON [City].[ProvinceId] = [Province].[Id]
   LEFT JOIN [Person] AS [Person] ON [City].[Id] = [Person].[CityId]
   ORDER BY [City].[Id] ASC
 */

更详细用法请参考 github 上的 demo