Typesafeing by getting Entity Framework entity column names
I'm currently binding to a control from code-behind.
For example:
var ctx = new MyEntities();
var source = from o in ctx.Users
select o;
myControl.DataSource = source;
开发者_JS百科 myControl.DataTextField = "SomeColumn1"; // Can I not typesafe this?
myControl.DataValueField = "Somecolumn2";
myControl.DataBind();
Ideally I'd like to get the property names from EF. Other ORMs tend to provide an Enum with all the available property names. Is this not the case with EF?
Whether or not the ORM has this as a built in function, you could do this yourself as an extension method using reflection.
Here it is in VB:
<Extension()>
Public Function PropertyName(Of T, TProperty)(ByVal targetObject As T, ByVal expression As Expression(Of Func(Of T, TProperty))) As String
Return DirectCast(expression.Body, Expressions.MemberExpression).Member.Name
End Function
So this would give you something like:
myControl.DataSource = source
myControl.DataTextField = source.First().PropertyName(Function(x) x.SomeColumn1)
myControl.DataValueField = source.First().PropertyName(Function(x) x.SomeColumn2)
myControl.DataBind()
(I'm using source.First() because the extension method is on an instance of the class, not a collection of instances)
And I note your original post is in C#:
[Extension()]
public string PropertyName<T, TProperty>(T targetObject, Expression<Func<T, TProperty>> expression)
{
return ((Expressions.MemberExpression)expression.Body).Member.Name;
}
And
myControl.DataSource = source;
myControl.DataTextField = source.First().PropertyName(x => x.SomeColumn1);
myControl.DataValueField = source.First().PropertyName(x => x.SomeColumn2);
myControl.DataBind();
精彩评论