除了尼古拉斯巴特勒和馬特(類型輸入類是使用T
)的評論暗示,我把一個提高尼古拉斯動態生成實體屬性的應答,功能二進制不需要發送field
作爲參數。
對於使用添加類作爲打擊:
public static class Helpers
{
public static Func<T, T> DynamicSelectGenerator<T>(string Fields = "")
{
string[] EntityFields;
if (Fields == "")
// get Properties of the T
EntityFields = typeof(T).GetProperties().Select(propertyInfo => propertyInfo.Name).ToArray();
else
EntityFields = Fields.Split(',');
// input parameter "o"
var xParameter = Expression.Parameter(typeof(T), "o");
// new statement "new Data()"
var xNew = Expression.New(typeof(T));
// create initializers
var bindings = EntityFields.Select(o => o.Trim())
.Select(o =>
{
// property "Field1"
var mi = typeof(T).GetProperty(o);
// original value "o.Field1"
var xOriginal = Expression.Property(xParameter, mi);
// set value "Field1 = o.Field1"
return Expression.Bind(mi, xOriginal);
}
);
// initialization "new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var xInit = Expression.MemberInit(xNew, bindings);
// expression "o => new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var lambda = Expression.Lambda<Func<T, T>>(xInit, xParameter);
// compile to Func<Data, Data>
return lambda.Compile();
}
}
的DynamicSelectGenerator
方法得到實體T
型,這種方法具有可選的輸入參數Fields
,如果你想從實體slect專業派作爲一個字符串,如"Field1, Field2"
,如果你不發送任何內容methid,它返回所有實體的字段,你可以使用下面這個方法:
using (AppDbContext db = new AppDbContext())
{
//select "Field1, Field2" from entity
var result = db.SampleEntity.Select(Helpers.DynamicSelectGenerator<SampleEntity>("Field1, Field2")).ToList();
//select all field from entity
var result1 = db.SampleEntity.Select(Helpers.DynamicSelectGenerator<SampleEntity>()).ToList();
}
(假設你有一個DbContext
與名稱AppDbContext
和上下文與名稱SampleEntity
)
是的,如果你的過濾器輸入是字符串 – 2013-05-13 07:39:39
@Congong如何?任何代碼示例或鏈接都會很棒。 – Unforgiven 2013-05-13 07:47:31
你想要結果類型是什麼? – 2013-05-13 07:50:12