0

我有一个场景,我需要根据运行时值选择要更新的属性之一。

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

有一个更好的方法吗 ?无论如何要在实体框架中连接字符串,这将允许我这样做

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

1 回答 1

2

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;
于 2016-02-15T14:59:05.347 回答