根据值更新实体属性

时间:2016-02-15 13:47:15

标签: c# entity-framework lambda entity-framework-extended

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

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

1 个答案:

答案 0 :(得分:2)

你可以使用这样的东西

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;