EF.Plus - Query Filter - Security Access (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Plus
// Doc: https://entityframework-plus.net/query-filter

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore

using System;
using System.Linq;
using Z.EntityFramework.Plus;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		GenerateData();

        using (var context = new EntityContext())
        {
            int myRoleID = 1;

            // CREATE filter by interface
            context.Filter<Post>(x => x.Where(q => q.RoleId >= myRoleID));

            // SELECT * FROM Posts WHERE RoleID >= 1
            var list = context.Posts.ToList();
        }
    }

    public static void GenerateData()
    {
        using (var context = new EntityContext())
        {
            context.Roles.Add(new Role() { Name = "Administrator" });
            context.Roles.Add(new Role() { Name = "HR" });
            context.Roles.Add(new Role() { Name = "Media" });

            context.Posts.Add(new Post() { Name = "Post_A", RoleId = 1 });
            context.Posts.Add(new Post() { Name = "Post_B", RoleId = 2 });
            context.Posts.Add(new Post() { Name = "Post_C", RoleId = 0 });
            context.Posts.Add(new Post() { Name = "Post_D", RoleId = 0 });

            context.SaveChanges();
        }
    }
	
	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}
		
		public DbSet<Post> Posts { get; set; }
        public DbSet<Role> Roles { get; set; }
    }


    public class Post
    {
        public int PostId { get; set; }
        public string Name { get; set; }
        public int RoleId { get; set; }
    }

    public class Role
    {
        public int RoleId { get; set; }
        public string Name { get; set; }
    }
}
;