Entity Framework soft delete implementation using database interceptor not working

前端 未结 2 822
面向向阳花
面向向阳花 2021-01-05 01:38

I have implemented a database soft delete (a boolean flag that marks entries as deleted) using the following tutorial: http://www.codeguru.com/csharp/csharp/soft-deleting-en

相关标签:
2条回答
  • 2021-01-05 01:45

    There is a bug in ApplicationDbContext.cs:

    protected new void OnModelCreating(DbModelBuilder modelBuilder) {...}
    

    You are using "new" instead of "override" so OnModelCreating is never executed (try to add a breakpoint to check it). So AttributeToTableAnnotationConvention never runs and entity annotation is never added.

    Changing it to

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {...}
    

    will make it work

    0 讨论(0)
  • 2021-01-05 01:56

    Well, you code seems fine to me. Perhaps there is a little mistake that is breaking your app. You could try this:

    1. Remove the SoftDeleteAttribute from BC_Instance

    2. Edit the OnModelCreating method

      AttributeToTableAnnotationConvention<SoftDeleteAttribute, string> conv =
         new AttributeToTableAnnotationConvention<SoftDeleteAttribute, string>(
            "SoftDeleteColumnName",
            (type, attributes) => attributes.Single().ColumnName);
      
      modelBuilder.Conventions.Add(conv);
      //this will dynamically add the attribute to all models
      modelBuilder.Types().Configure(delegate(ConventionTypeConfiguration i)
      {
          i.HasTableAnnotation("SoftDeleteColumnName", Entity.G etSoftDeleteColumnName());
      });
      
    3. Delete ApplicationDbConfiguration class

    4. Edit the context's constructor

      public ApplicationDbContext()
          : base("DefaultConnection", throwIfV1Schema: false)
      {
          DbInterception.Add(new SoftDeleteInterceptor());
      }
      

    Hope this helps!

    0 讨论(0)
提交回复
热议问题