根据值更新实体 属性

Update entity property based on 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

有更好的方法吗? 无论如何要在 entity framework 中连接字符串,这将允许我这样做

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

你可以使用这样的东西

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;