none
How To Insert List of Record To the Database Using Linq RRS feed

  • Question

  • Good day every one, Please i need little help, I have a list of record like this

    lblID.Text = string.Join("<br/>", numbers); gives the Numbers below... 6131 5241 3978 6824 3842

    //To Save to the database int pin = int.parse(lblID.Text); Now i want to insert those Numbers to the database Persons ps = new Persons(); ps.Number = pin; cdc.Persons.AddObject(ps); cdc.SaveChanges(); it throws up error... what i want to achieve on button insert all Numbers will be inserted but before inserting the number it will check if those numbers exist first on the database it should be like this on the database ID Number 1 6131 2 5241 3 3978 4 6824 5 3842 thanks.. I do appreciate your time and effort


    Monday, January 12, 2015 2:42 PM

Answers

  • Hello,

    >>Now i want to insert those Numbers to the database

    For inserting a list of items to database, a loop statement is needed. I do not how you get these numbers, I assume they are stored in a collection and you could check below demo sample to insert these numbers and I assume your person table is identified:

    using (DFDBEntities db = new DFDBEntities())
    
                    {
    
                        List<int> numbers = new List<int>() { 6131, 5241, 3978, 6824, 3842 };
    
                        for (int i = 0; i < numbers.Count; i++)
    
                        {
    
                            int number = numbers[i];
    
                            //Check if the local and database already contains this number
    
                            bool isRecordExist = db.Tables.Any(t => t.Number == number) || db.Tables.Local.Any(t => t.Number == number);
    
                            if (!isRecordExist)
    
                            {
    
                                Table t = new Table();
    
                                t.Number = number;
    
                                db.Tables.Add(t);
    
                            }
    
    
                        }
    
                        db.SaveChanges();
    
                    }
    

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, January 13, 2015 8:56 AM
    Moderator