0

I have a list of classes that I want to add to my database with a foreach loop in Entity Framework Core. How can I do it?

If I use the first method, only the last record is saved:

public void Create(List<Factor> f)
{
    DB db = new DB();

    foreach (var item in f)
    {    
        db.Factors.Add(item);
        db.SaveChanges();
    }
}

And if I use this method, the first record is saved, then the ASP.NET Core throws an error.

public void Create(List<Factor> f)
{
    DB db = new DB();

    foreach (var item in f)
    {    
        db.Factors.Add(item);         
    }    

    db.SaveChanges();
}

enter image description here

This is my factor class:

public class Factor
{
    [Key]
    public int id { get; set; }

    public bool DS { get; set; }
    public Guid FactorNumber { get; set; }

    public Book BookcodeFK { get; set; }
    public User UserCodeFK { get; set; }

    public int BookcodeFKid { get; set; }
    public string UserCodeFKId { get; set; }
    public int number { get; set; }
    public int TotalPrice { get; set; }

    public DateTime date { get; set; }
}

i edit my post: this is all the setting in DB class:

namespace DataAcessLayer
{



public  class DB : IdentityDbContext<User>
{

    public DB(): base() { }

    public DB(DbContextOptions<DB> options) : base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder OptionsBuilder)
    {
        OptionsBuilder.UseSqlServer(@"data source=DESKTOP-JU6B74R\SQL2019;initial catalog = OnlineBookShop; integrated security = true");
        base.OnConfiguring(OptionsBuilder);
    }

    public DbSet<Book> Books { set; get; }
    public DbSet<BookCategorization> BookCategorizations { set; get; }
    public DbSet<Comment> Comments { set; get; }
    public DbSet<Factor> Factors { set; get; }
    public DbSet<Notif> Notifs { set; get; }

    public DbSet<Cantact> Cantacts { set; get; }
}

}

1 Answer 1

1

The reason for the error is that You're inserting values for Factor Id that is an ‍‍identity column‍‍

This happens because for primary keys of type int (and some others) EF Core by default configures the database to generate the corresponding id on insert. If you want to take care of generating ids yourself mark your Id property with

[DatabaseGenerated(DatabaseGeneratedOption.None)] 
[Key]
public int id { get; set; }

Otherwhise, instead of explicitly assingn a value to the Factor Id property , let it be the default value (in this case 0) and EF will insert your entity and update the Id property to match the Id generated by the database when SaveChanges() is called.

also To insert multiples in the database, instead of using the loop, you can also use the ‍‍AddRange method as follows

public void Create(List<Factor> f)
{
   using(DB db = new DB())
   {
      db.Factors.AddRange(f);              
      db.SaveChanges();
    }
 }    
Sign up to request clarification or add additional context in comments.

5 Comments

i use this too but still only first record save
Pay attention to the first line of my answer, that is the reason for your error,Also include the Factor entity class and settings so I can help further
But i am not the set value for id this parameter always is 0
Have you made any settings in the ‍OnModelCreating method in the DBclass? If you have any settings, put them here
I set the break point for entire class and find my problem. after each time savechange is excited the id field for the next record automatically get value. so in the first line of each foreach loop i set the id to 0 manually. and the problem saved now. thanks for you help

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.