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