Linq to sql 使用Linq向SQL插入通过反射确定的对象

Linq to sql 使用Linq向SQL插入通过反射确定的对象,linq-to-sql,reflection,Linq To Sql,Reflection,我试图在给定键值列表的表中填充一行 使用DataContext.Mapping,我能够找到正确的表(给定一个表名)并创建一行 // Look up the table MetaTable matchedTable = null; foreach (MetaTable tableMetaData in db.Mapping.GetTables()) { if (table.Equals(tableMetaData.Table

我试图在给定键值列表的表中填充一行

使用DataContext.Mapping,我能够找到正确的表(给定一个表名)并创建一行

// 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");
        }
然后迭代行属性并填充值

// 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");
            }
        }
//遍历字典并尝试将键与列名匹配
foreach(列表中的KeyValuePair列表项)
{
PropertyInfo PropertyInfo=rowType.GetProperty(listItem.Key);
如果(propertyInfo==null)
{
抛出新异常(“指定的列名无效”);
}
//设置对象上的值
尝试
{
propertyInfo.SetValue(行,Convert.ChangeType(listItem.Value,propertyInfo.PropertyType),null);
}
抓住
{
抛出新异常(“指定的值无法转换为数据库类型”);
}
}
我现在需要将这个行对象插入到数据库中。我一直在玩
db.GetTable()我想得太多了

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