简体   繁体   中英

Retrieve/Update EF Entity using string representation of column - code first

Update : Im trying to update an EF entity without knowing the column until run time. So I would like my front end to post to my api with a column name and its value, then have my api update the database by:

  • Finding the column to be updated (using provided string)
  • Update db using provided value

So given the following data inside my webapi controller:

string colName = 'firstName';
string colValue = 'Sam';

In my EF data retrieval, instead of

var user = db.Users.Where(x => x.firstName == colValue);  //firstName is actual column name

can I do something like

var user = db.Users.Where(x => x.'colName' == x.colValue);  //colName is the string representation of column

and the somehow update this give column, so something like:

user.colName = colValue;  //where colName = 'firstName'

instead of

user.firstName = colValue;

I have researched Reflection quite a bit but I'm not sure where to begin or if such a task is even possible.

I could use a loop to retrieve like data like so:

foreach(var x in User.GetType().GetProperties()) {
if(x.ToString() == colName)
{
var y = db.User.Where(z => z.firstName == colValue)
}}

Any pointers, recommendations or suggestions would be greatly appreciated! Is this impossible?

Sorry, misread the question, here are the updated answer. You need to use:

var e = db.Entry(new User() {Id =1, Name = "test"});
var property = e.CurrentValues.PropertyNames.FirstOrDefault(p => p == colName);
e.CurrentValues[property] = colValue;

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