public void InsertListProducts(List <Product> products) { using (var connection = new NorthwindConnection("Northwind")) { try { connection.BeginTransaction(); foreach (var product in products) { var category = connection.Categories.FirstOrDefault(c => c.CategoryName == product.Category.CategoryName); product.CategoryId = category?.CategoryId ?? connection.InsertWithInt32Identity( new Category { CategoryName = product.Category.CategoryName }); var supplier = connection.Suppliers.FirstOrDefault(s => s.CompanyName == product.Supplier.CompanyName); product.SupplierId = supplier?.SupplierId ?? connection.InsertWithInt32Identity( new Supplier { CompanyName = product.Supplier.CompanyName }); } connection.BulkCopy(products); connection.CommitTransaction(); } catch { connection.RollbackTransaction(); } } }
public int AddNewEmployeeWithTerritories(Employee newEmployee) { using (var connection = new NorthwindConnection("Northwind")) { try { var a = connection.BeginTransaction(); newEmployee.EmployeeId = connection.InsertWithInt32Identity(newEmployee); connection.Territories.Where(t => t.TerritoryDescription.Length <= 5) .Insert(connection.EmployeeTerritories, t => new EmployeeTerritory { EmployeeId = newEmployee.EmployeeId, TerritoryId = t.TerritoryId }); connection.CommitTransaction(); return(newEmployee.EmployeeId); } catch { connection.RollbackTransaction(); return(0); } } }