问题描述
我有一个实体数据库,是从 sql 数据库创建的.我需要在 datagridview 上显示记录,我正在使用此代码.
I have a entity database, created from sql database. I need to show record on datagridview, i am using this code.
DBEntities db = new DBEntities();
dataGridView1.DataSource = db.Agent.Select(x => new { Name = x.Name, Second_Name = x.Second_Name}).ToList();
这是一个例子,真实的代理表包含大约 10 列,我需要显示所有,除了id".如果我每 8 列都做同样的事情,就会变成一个又长又无意义的行.怎么做才更健忘和好.
It's example, real agent table contain around 10 columns, and i need to show all, exept 'id'. If i do same for every 8 columns, become a long and senseless row. How to do it more obliviuous and good.
推荐答案
如果你不想使用匿名类型来指定你想要的字段,你可以:
If you don't want to use an anonymous type to specify the fields you want, you can:
- 在结果集中使用 ID,或者
- 包括
Select
中除 ID 之外的所有列,或 - 使用映射库,例如 AutoMapper.
- Live with having the ID in the result set, or
- Include all of the columns in the
Select
except for the ID, or - Use a mapping library, like AutoMapper.
Linq 中没有 Select except
语句.但是,您可以使用此扩展方法来完成相同的事情:
There's no Select Except
statement in Linq. However, you can use this extension method to accomplish the same thing:
/// <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>();
}
这篇关于如何从除某些列之外的表记录中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!