There is two way to insert multiple record in Database using EF.
1) As below example, we have to call AddRange method of DbSet class, here we can add multiple record as i have used EmpDetails list for adding multiple record.
using (var context = new DbContextDemo())
{
var item = context.EmpDetailsDbSet.ToList();
//Insert multiple record in sql table using EF
var list = new List<EmpDetails>(); // this is my Dbset class(EmpDetails)
EmpDetails obj = new EmpDetails()
{
EmpID = 23123,
EmpName = "ABC",
EmpAddress = "Test1",
EmpMobile = 1442345,
EmpCompany = "ABC"
};
list.Add(obj);
EmpDetails obj1 = new EmpDetails()
{
EmpID = 233,
EmpName = "ABC Test",
EmpAddress = "Bangalore",
EmpMobile = 1435235,
EmpCompany = "ABC Test"
};
list.Add(obj1);
context.EmpDetailsDbSet.AddRange(list); // Adding list of emp inside AddRange method
context.SaveChanges();
}
2) We will take same as above example, we will have list of EmpDetails and we are going to make foreach loop and add one by one record in Dbset class with Add method .
var list = new List<EmpDetails>();
EmpDetails obj = new EmpDetails()
{
EmpID = 23123,
EmpName = "ABC",
EmpAddress = "Test2",
EmpMobile = 1442345,
EmpCompany = "ABC"
};
list.Add(obj);
EmpDetails obj1 = new EmpDetails()
{
EmpID = 233,
EmpName = "ABC Test",
EmpAddress = "Bangalore",
EmpMobile = 1435235,
EmpCompany = "ABC Test"
};
list.Add(obj1);
foreach (var item1 in list) // Adding record one by one
{
context.EmpDetailsDbSet.Add(item1);
}
and finally call SaveChanges() method of context class.
context.SaveChanges();