How to replace the string value in extension method for lambda

124 views Asked by At

I would like to replace "PKMvrMedsProductIssuesId" for something like x=>x.PKMvrMedsProductIssueId or anything that is not based on a string. Why? Because if the database people choose to rename the field my program would crash.

public static SelectList MvrMedsProductErrors(this SelectList Object)
{
    MedicalVarianceEntities LinqEntitiesCtx = new MedicalVarianceEntities();
    var ProductErrorsListBoxRaw =
    (
        from x in LinqEntitiesCtx.ViewLookUpProductIssuesErrorsNames
        select x
    );

    Object = new SelectList(ProductErrorsListBoxRaw, "PKMvrMedsProductIssuesId", "MvrMedsProductIssuesErrorsNames");

    return Object;
}
2

There are 2 answers

1
Amy B On BEST ANSWER

You're using a SelectList. In order to call that constructor, you must have a string. Any change we could propose will still result in a string (from somewhere) being passed into that constructor.

The good news is: that string can come from anywhere. It can come from config, from the database... where ever you like.

1
doblak On

I don't know the exact context here (what exactly "PKMvrMedsProductIssuesId" is) , but you can for example use such helper method:

public static string GetPropertyAsString<T>(Expression<Func<T, object>> expression)
{
    return GetPropertyInfo(expression).Name;
}

To use an expression to get string:

GetPropertyAsString<MyType>(x => x.MyTypeProperty);

('MyTypeProperty' is your 'PKMvrMedsProductIssuesId' any 'MyType' one of your types where you may have your property defined)