Does this extension method contain unnecessary work? - Thanks for reviewing
Scenario - A series of tables are Key-Value pairs (Int "Id" / nvarChar "Title"). This extension method "dots-off" any integer ("Id") and provide the corresponding string value ("Title") given a target "type"
Used in aspx-code-behind. An extension method was chosen for readable one-liners. There are many panels with similar controls to be set conditionally.
// aspx.cs
txtParentGender.Text=parent.GenderId.RhGet(typeof(Gender)); //male, female
txtParentEthnicity.Text=parent.EthnicityId.RhGet(typeof(Ethnicity)); //Caucasian, etc.
txtParentMaritalStatus.Text=parent.MaritalStatusId.RhGet(typeof(MaritalStatus)); // married, divorced etc.
txtChildGender.Text=child.GenderId.RhGet(typeof(Gender));
txtChildEthnicity.Text=child.EthnicityId.RhGet(typeof(Ethnicity));
txtChildRelation.Text=child.RelationId.RhGet(typeof(Relation)); //son, daughter etc.
// class.cs
using System.Linq.Dynamic; // nuget package
public static string RhGet(this int id, Type type )
{
string returnValue = string.Empty;
// set up data context
using (MyDataContext dc = new MyDataContext())
{
// get table corresponding to this type
var table = dc.GetTable(type);
// match and select record using "id"
var matchingRecord = ((IQueryable)table).Where(string.Format("Id.Equals({0})", id))
.Select("new(Title)").Cast<object>().FirstOrDefault();
// do a lot of contorting to finally get the string value
returnValue = matchingRecord.GetType().GetProperty("Title").GetValue(matchingRecord,null).ToString();
}
return returnValue;
}
IQueryable.Where(string)
andIQueryable.Select(string)
? I'm not seeing it: msdn.microsoft.com/en-us/library/vstudio/… \$\endgroup\$table.Single(e => e.Id == id).Title
in your code? It's not problematic to have these types of queries sprinkled around your code without having a grand unifying method that everything with an ID/Title structure has to call, if you're worried about that. \$\endgroup\$