Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save list of entity with Entity Framework

How can I save a list of enitty into the database using Entity Framework Code First?

I have problem saving the list of entity.

Below is the code I have written:

List<Account> accounts = ActivateAccount();

// Save merchant account & bank information into database
using (var context = new MyContext())
{
    try
    {
        context.Accounts.Attach(accounts);
        context.SaveChanges();
    }
    catch (Exception ex)
    {

    }
}

Thank you.

like image 564
Alvin Avatar asked Oct 18 '25 00:10

Alvin


1 Answers

See the below link. Difference between Attach and AddToObject

Entity Framework 4 - AddObject vs Attach

Please clarify are you updating disconnected records or adding records. Below is the code to add records in DB.

using (var context = new MyContext())
{
    try
    {
        foreach(var row in accounts){
            context.AddToAccounts(row);
        }
        context.SaveChanges();
    }catch (Exception ex){
        //Log any exception here.
    }     
}
like image 194
sohail.hussain.dyn Avatar answered Oct 20 '25 13:10

sohail.hussain.dyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!