Transaction in EF
Earlier the System.Transactions namespace was used to handle transactions in the Entity Framework using TransactionScope and the Entity Framework uses this transaction to save the changes in the database.
From ver6, there is EntitiesContext
-
-
- using (EntitiesContext context = new EntitiesContext())
-
- {
- using (var transaction = context.Database.BeginTransaction())
- {
- try
- {
- EmployeeMaster employee = new EmployeeMaster();
- employee.Code = “A0001”;
- employee.Name = “Jignesh Trivedi”;
- employee.DepartmentId = 1;
- context.Employees.Add(employee);
- context.SaveChanges();
- DepartmentMaster dept = new DepartmentMaster();
- dept.Code = “DEP0001”;
- dept.Name = “Department 1”;
- context.Departments.Add(dept);
- context.SaveChanges();
- transaction.Commit();
- }
- catch (Exception ex)
- {
- transaction.Rollback();
- }
- }
- }
-
From <http://www.c-sharpcorner.com/UploadFile/ff2f08/working-with-transaction-in-entity-framework-6-0/>
Database first vs Schema First vs Code first approaches:
Fluent API in code-first:
https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
http://www.entityframeworktutorial.net/code-first/fluent-api-in-code-first.aspx
EF code-first data annotations:
https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx
EF code migrations: If we make any change to model, that has to be updated to database. Use package manager console for this update using migrations feature. It’s a 3-step process.
-
-
- Enable-migrations
- Add-migration name
- Update-Database -Verbose
-
Ex: If more than one context exists
Enable-Migrations -ContextTypeName EFLibrary.SQLContext
Add-Migration AddDescriptionCategory
Update-Database –Verbose
To generate db script for migration – Update-database -SourceMigration: $InitialDatabase -TargetMigration: <migration file name>