2010-09-22 37 views
3

我试图填充给出一个键值列表插入使用LINQ到SQL通过反射

使用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"); 
      } 
     } 

我现在需要把这个行对象插回到数据库中。我一直玩db.GetTable<rowType>();没有运气。由于

回答

1

我被它得太多

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

或underthinking它;) – 2010-09-22 19:20:46