简体   繁体   中英

Update entity property based on value

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM