Dynamic LINQ - Entity Framework 6 - Update Records for Dynamic Select

c# dynamic-linq entity-framework-6

Question

rookie C#. Here is my code; I've been trying to get it to update various columns in my database for hours and have tried many implementations without success.

        // Select all fields to update
        using (var db = new Entities())
        {
            // dbFields are trusted values
            var query = db.tblRecords
                         .Where("id == " + f.id)
                         .Select("new(" + string.Join(",", dbFields.Keys) + ")");

            foreach (var item in query)
            {
                foreach (PropertyInfo property in query.ElementType.GetProperties())
                {
                    if (dbFields.ContainsKey(property.Name))
                    {
                        // Set the value to view in debugger - should be dynamic cast eventually
                        var value = Convert.ToInt16(dbFields[property.Name]);
                        property.SetValue(item, value);

                        // Something like this throws error 'Object does not match target type'
                        // property.SetValue(query, item);
                    }
                }
            }
            db.SaveChanges();
        }

When the aforementioned code is executed, the DB is left untouched. Obviously, this code needs some cleaning, but my goal is to get the essential features to operate. I think I may need to somehow reapply the "item" to the "query," but I can't seem to make it work; no matter what implementation I attempt, I always get the error message "Object does not match target type."

This somewhat related problem confirms that, but it's not quite apparent to me since I'm using a Dynamic LINQ query and can't simply directly link to the property names. https://stackoverflow.com/a/25898203/3333134

1
0
5/23/2017 10:32:41 AM

Accepted Answer

Updates will be made for you by Entity Framework on entities rather than custom outcomes. YourtblRecords houses a variety of entities, and if you want Entity Framework to be helpful, you should deal with this. the call to remove your projection)Select ) and the query will immediately return the objects (yeah, with an excessive number of columns, but we'll discuss that later).

Given that you have a standard object to deal with, the dynamic update is carried out in the same manner as any other dynamic assignment in C#. Your modifications will be tracked by Entity Framework, and when you callSaveChanges , will create and run the associated SQL queries.

You may alternatively execute the update from memory, However, if you wish to optimize and cease picking and constructing all the values in memory at once, including those that aren't required. You may use the Attach() method to add an object to the current context if you independently construct one of the proper types and provide it the appropriate ID. Any modifications made after that will be noted by Entity Framework, and when you callSaveChanges the database should get everything:

// Select all fields to update
using (var db = new Entities())
{
    // Assuming the entity contained in tblRecords is named "ObjRecord"
    // Also assuming that the entity has a key named "id"
    var objToUpdate = new ObjRecord { id = f.id };

    // Any changes made to the object so far won't be considered by EF

    // Attach the object to the context
    db.tblRecords.Attach(objToUpdate);

    // EF now tracks the object, any new changes will be applied

    foreach (PropertyInfo property in typeof(ObjRecord).GetProperties())
    {
        if (dbFields.ContainsKey(property.Name))
        {
             // Set the value to view in debugger - should be dynamic cast eventually
             var value = Convert.ToInt16(dbFields[property.Name]);
             property.SetValue(objToUpdate, value);
        }
    }

    // Will only perform an UPDATE query, no SELECT at all
    db.SaveChanges();
}
1
11/2/2016 1:01:17 PM

Popular Answer

When you performSELECT NEW ... It doesn't keep track of changes for you and only chooses certain fields. I believe your query will succeed if you update it to be this:

var query = db.tblRecords.Where(x=>x.id == id);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow