-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How should I listen for entities being added/deleted/modified in ef core? #5970
Comments
@kagamine There isn't public API to do this in EFCore 1.0. This is being tracked by #626. However, you can do it by accessing our internal services. But be aware that we may change these APIs in future releases which may cause your application to break when updated to a new version of EF. That being said, if you are okay with it, then here is a small console app showing how to do in 1.0: public class StateListener : IEntityStateListener
{
public void StateChanging(InternalEntityEntry entry, EntityState newState)
{
Console.WriteLine(
" Changing {0} from {1} to {2}.",
entry.Entity.GetType().Name, entry.EntityState, newState);
}
public void StateChanged(InternalEntityEntry entry, EntityState oldState, bool skipInitialFixup, bool fromQuery)
{
Console.WriteLine(
" Changed {0} from {1} to {2}.",
entry.Entity.GetType().Name, oldState, entry.EntityState);
}
}
public class MyContext : DbContext
{
private static readonly IServiceProvider _serviceProvider
= new ServiceCollection()
.AddEntityFrameworkSqlServer()
.AddSingleton<IEntityStateListener>(new StateListener())
.BuildServiceProvider();
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseInternalServiceProvider(_serviceProvider)
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ListenerTest;Trusted_Connection=True;");
}
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
}
public class Program
{
public static void Main()
{
using (var context = new MyContext())
{
context.Database.EnsureCreated();
var blog = new Blog() { Title = "Blog Titlle" };
Console.WriteLine("Adding...");
context.Add(blog);
Console.WriteLine("Saving...");
context.SaveChanges();
blog.Title = "Changed Title";
Console.WriteLine("Detecting change...");
context.ChangeTracker.DetectChanges();
Console.WriteLine("Saving...");
context.SaveChanges();
}
}
} Things to note here:
Hope this helps. I'm going to close this issue as a dupe of #626. |
Wow! Thanks! |
You can find some usefull informations at this post https://stackoverflow.com/questions/53187146/populate-created-and-lastmodified-automagically-in-ef-core#answer-53188193 |
@rowanmiller
The text was updated successfully, but these errors were encountered: