Home > other >  How can add list of class to database with Entity Framework Core?
How can add list of class to database with Entity Framework Core?

Time:09-17

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; }
}

}

CodePudding user response:

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();
    }
 }    
  • Related