Entity Framework - ObjectContext or DbContext when AuditLog and CreatedOn/ModifiedOn and DB Modeling Team

StackOverflow https://stackoverflow.com/questions/14791197

  •  07-03-2022
  •  | 
  •  

Question

Which one to choose either ObjectContext or DbContext, when the requirements are,

  1. Data Modeling done by Modeler and provides the DEV team a sql script. Due to this we have opted Model First. Is this a correct choice ?
  2. Existing denormalized db will be migrated to new db created by modeler
  3. Need to maintain audit log for all the updates, at the field level, from the UI
  4. Each table has CreatedBy, CreatedOn, ModifiedBy, ModifiedOn. These fields should be automatically filled by during context.SaveChanges().
Was it helpful?

Solution

If you're starting a new app, just use DbContext. You can always drill down to ObjectContext if you need to.

  1. If you prefer no designer, you can use Code First with Migrations and create a SQL Script via update-database -script as well.

  2. Sounds like a task for the DBAs?

  3. field by field changes..If this is a disconnected app, you'll be better off handling that outside of EF (IMHO)

  4. you can easily override SaveChanges for this. You said in a tweet that you have the dbcontext book. There's an example of this where we do this using a base class. However if you are going to use model first, be sure to avoid this problem : http://msdn.microsoft.com/en-us/magazine/jj553510.aspx

OTHER TIPS

Thanks a lot Julie for your super quick response. You are The-EF-Angel.
I have read your MSDN article on Logging in EF.
To your reponse:

1. As a mandate, We need to use sql scripts provided by our Modeler to create our db. Also these scripts will be keep changing(With addition of new tables & update of exising schema) for each sprints. Hope DataFirst Model is fine. Whenever new we get new sql scripts, we plan to recreate the DB and update our EDMX. Do you see any issues with this approach ?

2. Ya we have a migration specialist for this task. I justed pointed that in question as an FYI.

3. We use MVC app and for field by field changes in audit log table, we planned to let EF decide what fields have changed(using change tracking ideas from your book) and capture that info into a DTO(we borrow your repository ideas from the course "EF in enterprise course" you authored in PS). And push that DTO into our messaging infrastructure and that will insert the audit logs to the DB.
Is this fine ? Do you foresee any issues ?

4. As you pointed out, we could change our interface for our needs by referring to your MSDN article and there "Figure 3 Setting the Interface’s DateCreated Property During SaveChanges"

I plan to use,
public interface ITheBaseType 
{

  DateTime DateCreated { get; set; }
  DateTime DateModified { get; set; }
  string   CreatedBy { get; set; }
  string   ModifiedBy { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top