Entity Framework – Notes

DBEntityEntry enables you to access entity state, current, and original values of all the property of a given entity.​

DBEntityEntry studentEntry = dbcontext.Entry(StudentEntity);


studentEntry.Reload(); // reload entity from DB, discard in-memory changes..
Or mark an entry as modified manually – (ready to update db on save)
studentEntry.State = ​System.Data.Entity.EntityState.Modified​;

​​​EF Change Tracking (CT):

## How many entries are being tracked by context:

context.ChangeTracker.Entries().Count()

## Enlist entires and their state :

​Foreach (var entry in entries)
Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName);
Console.WriteLine("Status: {0}", entry.State);

​## Disable change tracking (performance boost, esp for readonly operations)

context.Configuration.AutoDetectChangesEnabled = false

## Detecting changes when CT disabled before Saving

context.ChangeTracker.DetectChanges() // marks entries as modified, added or deleted etc.

context.SaveChanges()

Caution: Working with List of Entities – only updates work

var studentList = context.Students.ToList();

studentList.Add(new Student{…}) // no insert called for this in DB

studentList.RemoveAt(0) // no delete called for this in DB

​//Perform update operation

    Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";​

// use DBSet operations to Add/Delete entries using Add, Attach, Remove. Note: Add will attach whole Student object-graph in Added state. Whereas Attach​ will attach the obj-graph in an unchanged state.

ctx.Students.Add(new Student{…}​​​​);

## Mark PK column as Non -Identity – by default int Key column is Identity (1,1)

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)​​]

​Handle concurrency conflicts – DBConcurrencyException

​​http://www.infoworld.com/article/3085390/application-development/how-to-handle-concurrency-conflicts-in-entity-framework.html​

catch(DBConcurrencyException ex)

   var entry = ex.Entries.Single();  // get the entry from db which has concurrency issue

   if (entry != null) // null means entry is deleted, so act accordingly..

     entry.OriginalValues.SetValues(entry.GetDatabaseValues());​ // Set Original values again so we have refreshed entity in context

      ​​      context.saveChanges(); // try saving again..

​## LAZY Loading and Virtual Keyword

Lazy loading is ON by default. And any prop declared public virtual will be lazy loaded. NON-virtual properties are always eager loaded.

To turn off Lazy loading at property level – make that property non-virtual (remove virtual keyword). This is entity level control.

To turn off Lazy loading at Context level set it in context constructor –

this.Configuration.LazyLoadingEnabled = false;​

## With Lazy Loading enabled, we can force loading child entities as:

ctx.Entry(student).Reference(s => s.Standard).Load(); // Loading a Navigation Property (non-collection)

ctx.Entry(student).Collection(s => s.Courses).Load(); // loading a collection of courses

Leave a Reply

Your email address will not be published. Required fields are marked *