4

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.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Alvin
  • 8,219
  • 25
  • 96
  • 177

3 Answers3

3

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.
    }     
}
Community
  • 1
  • 1
sohail.hussain.dyn
  • 1,411
  • 1
  • 16
  • 26
0
List<Account> accounts = ActivateAccount();

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

    }
}

Try replacing Attach method with Add

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Rajeev.Ranjan
  • 273
  • 1
  • 3
  • 14
0

I found several ways to do it in this post https://stackoverflow.com/a/12853252/7287324

Hope it solves your problem.

Chemah
  • 538
  • 6
  • 18