Skip to content
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

Closed
yukozh opened this issue Jul 4, 2016 · 3 comments
Closed

Comments

@yukozh
Copy link
Contributor

yukozh commented Jul 4, 2016

@rowanmiller

@yukozh yukozh changed the title How should I listen for entities being added/deleted in ef core? How should I listen for entities being added/deleted/modified in ef core? Jul 4, 2016
@ajcvickers
Copy link
Contributor

@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:

  • You need a class that implements IEntityStateListener. This will get the notifications
  • This class must be registered in the dependency injection container. In the example I am adding a single instance to the D,I, container, but how you do it in your app depends on how you ultimately need to use the notifications.
  • You need to tell EF to use the service provider created from this D.I. container. I am creating a static instance of the service provider and registering it in OnConfiguring. If you are using ASP.NET then you will likely want to do this in AddDbContext instead.

Hope this helps. I'm going to close this issue as a dupe of #626.

@yukozh
Copy link
Contributor Author

yukozh commented Jul 8, 2016

Wow! Thanks!

@rdhainaut
Copy link

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
@ajcvickers ajcvickers removed their assignment Sep 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants