2016-02-15 100 views
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); 
+0

請詳細說明一下你的意思。你可以在實體框架中連接字符串 – Eldho

+0

它在我後面的內容中非常詳細。 – wk4questions

回答

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;