开发者

ASP.NET - How to save a List Collection to DB using Stored Procedure?

I have a List Collection:

 List<Person> people = new List<Person>();

    Person p1 = new Person();

    p1.FirstName = "Nikos";
    p1.LastName = "Kantzelis";
    p1.Email = "nikolaosk@hotmail.com";
    p1.Height = 1.78m;
    p1.Weight = 88.5m;


    Person p2 = new Person();

    p2.FirstName = "James";
    p2.LastName = "Ro开发者_如何学JAVAwling";
    p2.Email = "jamesr@hotmail.com";
    p2.Height = 1.98m;
    p2.Weight = 98.25m;

    Person p3 = new Person();

    p3.FirstName = "George";
    p3.LastName = "Graham";
    p3.Email = "graham@yahoo.co.uk";
    p3.Height = 1.88m;
    p3.Weight = 81.5m;

    people.Add(p1);
    people.Add(p2);
    people.Add(p3);

Now I want to save the values inside this List Collection to some of my tables in DB using a stored procedure.

Please advise.

Regards, Pawan


I'm not sure if you're looking for something fancier, but you can do something like this:

foreach (Person person in people)
{
    //example code
    //save each person in the list to the database
    SavePerson(person.Name, person.Age, ...); 
}

If you'd rather, you can also do it with LINQ like this:

//example code
//save each person in the list to the database
people.ForEach(person => SavePerson(person.Name, person.Age, ...));


If your DB is SQL 2005 (or is it 2008) and above, you could serialize the list of objects to XML, then pass the whole XML blob to the SP in a parameter then use MSSQL's XML query capabilities to parse the XML and insert the data into the table.

Sort of a INSERT INTO Person SELECT * FROM XML

That would allow a single SP call and it could be wrapped in a transaction within the SP (rather than crossing process boundaries).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜