开发者

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?

I开发者_StackOverflows 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜