ORM

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

      1. using (EntitiesContext context = new EntitiesContext())  
      1. {  
      2.     using (var transaction = context.Database.BeginTransaction())  
      3.     {  
      4.         try  
      5.         {  
      6.             EmployeeMaster employee = new EmployeeMaster();  
      7.             employee.Code = “A0001”;  
      8.             employee.Name = “Jignesh Trivedi”;  
      9.             employee.DepartmentId = 1;  
      10.             context.Employees.Add(employee);  
      11.             context.SaveChanges();  
      12.   
      13.             DepartmentMaster dept = new DepartmentMaster();  
      14.             dept.Code = “DEP0001”;  
      15.             dept.Name = “Department 1”;  
      16.             context.Departments.Add(dept);  
      17.             context.SaveChanges();  
      18.   
      19.             transaction.Commit();  
      20.         }  
      21.         catch (Exception ex)  
      22.         {  
      23.             transaction.Rollback();  
      24.         }  
      25.     }  
      26. }  

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.

      1. Enable-migrations
      2. Add-migration name
      3. 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>

Leave a comment