简体   繁体   中英

Entity Framework - Loop through properties for update

I am trying to find a way to loop through the properties of an EF object and update the values of these properties. More specifically I have 50 fields that are populated by up to 50 dropdownlists. All 50 may or may not need to be populated.

To solve this I have a repeater that will create up to 50 DDL. The user will select the values for each one and then press an update button. I am looping through the items in the repeater and can keep count of which iteration I am on in the repeater. I want to also use this count to know what field I need to update. For instance DDL1 = FIELD1, DDL2 = FIELD2, ....).

Here is an example of what I am trying to do:

using (Data.Entities dataContext = new Data.Entities)
{
    var efObject = dataContext.EFData.Where(c => c.ID = [SOMEID]).First();

    int posCount = 0;
    foreach (RepeaterItem rep1 in repeaterControl.Items)
    {
        DropDownList ddlControl= (DropDownList)rep1.FindControl("ddlControl");

        //Here is where I need to update a field
        //Something like:  efObject.Field# = ddlControl.SelectedValue;
    }
}

Is there any way to dynamically create the property name I need to update?

Is there some property collection I can access by index?

Is this even remotely close to how I should be going about this?

Any and all help will be much appreciated. Thank you.

You could do something like this.

var properties = typeof(EFType).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
    var control = (DropDownList)rep1.FindControl("ddlControl" + property.Name);
    property.SetValue(efObject, control.SelectedValue, null);
}

SelectedValue is string. So you need to take care of type conversion if needed.

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