Skip to content

Instantly share code, notes, and snippets.

@hikalkan
Created July 27, 2016 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hikalkan/4b0df93c8e95b08120e8cb7cd7f7cded to your computer and use it in GitHub Desktop.
Save hikalkan/4b0df93c8e95b08120e8cb7cd7f7cded to your computer and use it in GitHub Desktop.
EfPlus Demo Soft Delete Filtering with EF Core
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;
namespace EfPlusDemo
{
public class Program
{
public static void Main(string[] args)
{
QueryFilterManager.Filter<Blog>(q => q.Where(b => !b.IsDeleted));
QueryFilterManager.Filter<Post>(q => q.Where(p => !p.IsDeleted));
ListBlogsAndPosts();
Console.ReadLine();
}
private static void ListBlogsAndPosts()
{
using (var db = new BloggingContext())
{
Console.WriteLine("ListBlogsAndPosts:");
Console.WriteLine();
foreach (var blog in db.Blogs.ToList())
{
Console.WriteLine("- {0}", blog);
foreach (var post in db.Posts.Where(p => p.Blog == blog).ToList())
{
Console.WriteLine(" - {0}", post);
}
}
}
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public BloggingContext()
{
QueryFilterManager.InitilizeGlobalFilter(this);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=localhost;Database=EfPlusDemo1;Trusted_Connection=True;");
}
}
public class Blog : ISoftDelete
{
public int BlogId { get; set; }
public string Url { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("BlogId")]
public List<Post> Posts { get; set; }
public override string ToString()
{
return $"BlogId={BlogId}, Url={Url}, IsDeleted={IsDeleted}";
}
}
public class Post : ISoftDelete
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[ForeignKey("BlogId")]
[Required]
public Blog Blog { get; set; }
public bool IsDeleted { get; set; }
public override string ToString()
{
return $"PostId={PostId}, Title={Title}, Content={Content}, IsDeleted={IsDeleted}";
}
}
public interface ISoftDelete
{
bool IsDeleted { get; set; }
}
}
@alebrozzoSP
Copy link

Since you are implementing an interface, can't you just do
QueryFilterManager.Filter<ISoftDelete>(q => q.Where(b => !b.IsDeleted)); ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment