2010-07-15 3 views
0

아래 코드를 사용하고 싶습니다. 그래서 일반 목록이 있습니다 < MyClass > 나는 System.Reflection을 사용하여 사용해야한다고 생각합니다. 메서드 < MyClass > 문자열 [] columnNames, object [] columnValues를 채우기 위해 속성을 사용할 수 있지만 어떻게 사용할 수 있습니까?동적 삽입 사용 방법 - linq to sql?


foreach (var item in List<myClass>) 
    { 
     // i want to fill get columnNames and values to fill below arrays how to? 
    } 


public static class MyExtensionMethod 

    { 

     public static bool DynamicInsertCustomerExtension(this MyDataContext db, string[] columnNames, object[] columnValues) 

     { 

      try 

      { 

       if (columnNames.Length == 0 || columnValues.Length == 0) 

       { 

        throw new Exception("Column Name or Column Value array is empty!"); 

       } 



       if (columnNames.Length != columnValues.Length) 

       { 

        throw new Exception("Column Name array and Column Value array are in different length!"); 

       } 



       TBL_Customer entity = new TBL_Customer(); 



       for (int i = 0; i < columnNames.Length; i++) 

       { 

        entity.GetType().GetProperty(columnNames[i]).SetValue(entity, columnValues[i], null); 

       } 



       db.TBL_Customers.InsertOnSubmit(entity); 



       return true; 



      } 

      catch (Exception ex) 

      { 

       MessageBox.Show(ex.Message); 

       return false; 

      } 

     } 

    } 

답변

0

이 매우 작업에 지나치게 복잡해 보인다. 당신이하려는 일을 정확하게 보는 것은 어렵습니다. MyClass의 목록이 있고 MyClass 개의 항목을 모두 TBL_Customers으로 표에 넣으 려한다고 가정하는 것이 맞습니까? 다음과 같이 시도해보십시오.

public void InsertAll(List<MyClass> items) { 
    var itemsAsCustomers = items.Select(item => new TBL_Customer 
    { 
     ID = item.UserID, 
     Username = item.UsernamePropertyOnMyClass, 
    }); 

    db.TBL_Customers.InsertAllOnSubmit(itemsAsCustomers); 
    db.SubmitChanges(); 
}