Insert with Linq-to-SQL an object defined by reflection

I am trying to fill a row in a table given a list of key values

Using DataContext.Mapping I can find the correct table (given the name of the table) and create a row.

// Look up the table
        MetaTable matchedTable = null;

        foreach (MetaTable tableMetaData in db.Mapping.GetTables())
        {
            if (table.Equals(tableMetaData.TableName))
            {
                matchedTable = tableMetaData;
                break;
            }
        }

        if (matchedTable == null)
        {
            throw new Exception("Invalid table name specified");
        }

Then I repeat the properties of the string and fill in the values.

// Iterate through the dictionary and try to match up the keys with column names
        foreach (KeyValuePair<string, string> listItem in list)
        {
            PropertyInfo propertyInfo = rowType.GetProperty(listItem.Key);

            if (propertyInfo == null)
            {
                throw new Exception("Invalid column name specified");
            }

            // Set the value on the object
            try
            {
                propertyInfo.SetValue(row, Convert.ChangeType(listItem.Value, propertyInfo.PropertyType), null);
            }
            catch
            {
                throw new Exception("Value specified cannot be converted to database type");
            }
        }

Now I need to return this row object back to the database. I have not played with db.GetTable<rowType>();. Thanks

+3
source share
1 answer

I overestimated him

db.GetTable(rowType).InsertOnSubmit(row);
db.SubmitChanges();
+1
source

Source: https://habr.com/ru/post/1766060/


All Articles