ApplicationDbContext.cs 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18




using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Aurora.Common.Entities;
using Aurora.Core.Domain.Entities;
using Aurora.Infrastructure.Tenant;
using Aurora.Infrastructure.User;
using Microsoft.EntityFrameworkCore;

namespace Aurora.Core.EntityFramework
{
19
    public class ApplicationDbContext : DbContext
20
    {
21 22 23 24
        private readonly ICurrentUser currentUser;
        private readonly ICurrentTenant currentTenant;

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
25
        {
lwplvx's avatar
lwplvx 已提交
26 27 28
            // ,
            // ICurrentUserProvider currentUserProvider,
            // ICurrentTenantProvider currentTenantProvider
29 30
            // currentUser = currentUserProvider.GetCurrentUser();
            // currentTenant = currentTenantProvider.GetCurrentTenant();
31 32
        }

33 34 35
        public DbSet<Category> Categories { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
36
        {
S
simon 已提交
37 38
            //配置正在运行的程序集里所有实体映射配置类
            builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
39 40 41 42 43 44 45 46

            //多租户过滤
            foreach (var type in GetBaseEntityTypes())
            {
                var method = SetGlobalQueryMethod.MakeGenericMethod(type);
                method.Invoke(this, new object[] { builder });
            }

S
simon 已提交
47 48 49
            // 配置表名映射
            builder.Entity<Category>().ToTable("category");
 
50
            base.OnModelCreating(builder);
51 52
        }

53 54 55
        private static IList<Type> _baseEntityTypesCache;

        private static IList<Type> GetBaseEntityTypes()
56
        {
57 58 59 60 61 62
            if (_baseEntityTypesCache != null)
                return _baseEntityTypesCache.ToList();
            _baseEntityTypesCache = (from t in typeof(TenantEntityBase).GetTypeInfo().Assembly.DefinedTypes
                                     where t.BaseType == typeof(TenantEntityBase)
                                     select t.AsType()).ToList();
            return _baseEntityTypesCache;
63
        }
64 65
        protected static readonly MethodInfo SetGlobalQueryMethod = typeof(ApplicationDbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                                        .Single(t => t.IsGenericMethod && t.Name == "SetGlobalQuery");
66

67
        public void SetGlobalQuery<T>(ModelBuilder builder) where T : TenantEntityBase
68
        {
69
            builder.Entity<T>().HasQueryFilter(e => e.TenantCode == currentTenant.TenantCode);
70 71 72
        }
    }
}