Let's assume this Entity Framework sample:
public class User
{
public int UserID { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new MyDbContext ())
{
var user = new User { Name = "Foo"};
db.Users.Add(user);
db.SaveChanges();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
I want add to User class events, like "BeforeInsert" or "BeforeUpdate", and when the code...
db.Users.Add(user);
... is executed anywhere in the application, the "BeforeInsert" method will be raised. Is it possible?
@JC's answer is correct. I will just show code, in which you can do what you want. First of all, override SaveChanges method in your context, and call this overriden SaveChanges method: context.SaveChanges(true) instead of conntext.SaveChanges()
Your CustomContextManager class should look like this. Performing your before update operations in PerformBeforeUpdate method. You can add your own PerformBeforeInsert and/or PerformBeforeDelete methods.
You want to do that in an override of the
SaveChanges()
method of yourDbContext
. Scan through theChangeTracker.Entries
collection for any entries of your type. Then for each of those, do your BeforeInsert or BeforeUpdate operations based on whetherentry.State
isEntityState.Added
orEntityState.Modified
.