开发者

Insert with Linq-to-SQL an object determined through reflection

开发者 https://www.devze.com 2023-01-17 08:54 出处:网络
I am trying to populate a row in a table given a key value list Using DataContext.Mapping I am able to locate the correct table (given a table name) and create a row.

I am trying to populate a row in a table given a key value list

Using DataContext.Mapping I am able to locate the correct table (given a table name) 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");
        }

I then iterate over the row properties and populate 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");
            }
        }

I now need to get this row object inserted back into the DB. I have been playing around with db.GetTable<rowType>(); with no luck. Thanks


I was overthinking it

db.GetTable(rowType).InsertOnSubmit(row);
db.SubmitChanges();
0

精彩评论

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