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.

1
  • 1
    Are these new accounts or existing? Commented Sep 10, 2012 at 4:06

3 Answers 3

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.
    }     
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Hope it solves your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.