Reputation: 135
I have a scenario where I need to pick one of the properties to update based on run time value.
Person
PersonId
PeriodAge1
PeriodAge2
PeriodAge3
..
Period50
int currentPeriod = GetCurrentPeriodFromWhereEver();
Person p = Context.Persons.where(p=>p.PersonId=="Doe").firstOrDefault();
if(currentPeriod==1)
p.PeriodAge1 = 10
else if (currentPeriod==2)
p.PeriodAge2 = 112
...
else if (currentPeriod==50)
p.PeriodAge50 = 221
Is there a better way to do this ? Is there anyway to concatenate string in entity framework, something that will allow me to do this
string pAge = "PeriodAge";
string cPeriod = "5";
string combinedProperty = pAge + cPeriod; //PeriodAge5
Person p = Context.Persons.where(p=>p.PersonId=="Doe")
.FirstOrDefault()
.Update(p=>combinedProperty = 111);
Upvotes: 0
Views: 65
Reputation: 205629
You can use something like this
string pAge = "PeriodAge";
string cPeriod = "5";
string combinedProperty = pAge + cPeriod; //PeriodAge5
var person = Context.Persons.FirstOrDefault(p => p.PersonId == "Doe");
// The essential part:
Context.Entry(person).Property(combinedProperty).CurrentValue = 111;
Upvotes: 2