开发者

how to use dynamic insert - linq to sql?

开发者 https://www.devze.com 2023-01-07 01:35 出处:网络
i want to use below codes. So i have a generic list<MyClass> i think that i should use using System.Reflection; method to get list<MyClass>

i want to use below codes. So i have a generic list<MyClass> i think that i should use using System.Reflection; method to get list<MyClass> property to fill string[] columnNames, object[] columnValues but how can i use it?


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!");

                }



     开发者_如何学Python           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;

            }

        }

    }


This looks extremely over-complicated for the task. It's hard to see exactly what you're trying to do. Am I right to assume that you've got a list of MyClass and want to insert all of the MyClass items as TBL_Customers into a table? You probably want to try something like this:

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();
}
0

精彩评论

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

关注公众号