c# - 如何从表记录中选择除某些列外的记录

标签 c# linq entity-framework datagridview linq-to-entities

我有一个实体数据库,是从 sql 数据库创建的。我需要在 datagridview 上显示记录,我正在使用这段代码。

DBEntities db = new DBEntities();
dataGridView1.DataSource = db.Agent.Select(x => new { Name = x.Name, Second_Name = x.Second_Name}).ToList();

例如,真实代理表包含大约 10 列,我需要显示所有列,除了“id”。如果我每 8 列都做同样的事情,就会变成一长串毫无意义的行。如何做得更健忘和更好。

最佳答案

如果你不想使用匿名类型来指定你想要的字段,你可以:

  1. 接受结果集中的 ID,或者
  2. 包括 Select 中除 ID 之外的所有列,或者
  3. 使用映射库,例如 AutoMapper。

Linq 中没有Select Except 语句。但是,您可以使用此扩展方法来完成同样的事情:

/// <summary>
/// Returns all fields/properties from <paramref name="source"/> except for the field(s)/property(ies) listed in the selector expression.
/// </summary>
public static IQueryable SelectExcept<TSource, TResult>( this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector )
{
    var newExpression = selector.Body as NewExpression;

    var excludeProperties = newExpression != null
            ? newExpression.Members.Select( m => m.Name )
            : new[] { ( (MemberExpression)selector.Body ).Member.Name };

    var sourceType = typeof( TSource );
    var allowedSelectTypes = new Type[] { typeof( string ), typeof( ValueType ) };
    var sourceProperties = sourceType.GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where( p => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (PropertyInfo)p ).PropertyType ) ) ).Select( p => ( (MemberInfo)p ).Name );
    var sourceFields = sourceType.GetFields( BindingFlags.Public | BindingFlags.Instance ).Where( f => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (FieldInfo)f ).FieldType ) ) ).Select( f => ( (MemberInfo)f ).Name );

    var selectFields = sourceProperties.Concat( sourceFields ).Where( p => !excludeProperties.Contains( p ) ).ToArray();

    var dynamicSelect = 
            string.Format( "new( {0} )",
                    string.Join( ", ", selectFields ) );

    return selectFields.Count() > 0
        ? source.Select( dynamicSelect )
        : Enumerable.Empty<TSource>().AsQueryable<TSource>();
}

延伸阅读
Use SelectExcept When You Are Too Lazy to Type

关于c# - 如何从表记录中选择除某些列外的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205761/

相关文章:

vb.net linq查询where子句中的iif条件

c# - Automapper、MapFrom 和 EF 动态代理

c# - 打开: underlying provider failed on Open

c# - 如何使用 EntityFramework 调用存储过程?

c# - Xamarin - 如何在不使用其他服务的情况下发送推送通知

c# - (几乎)所有垃圾收集都是完全收集

c# - winforms大段落工具提示

c# - 无需手动多次循环即可将文本添加到列表所有项目的所有属性

c# - 共享连接字符串

c# - 转换为值类型 'System.Int32' 失败,因为具体化值为空。