Skip to content

kambalin/efdm

Repository files navigation

EFDM

Entity Framework Data Manager

NuGet

NuGet Status NuGet Count

Package targets .NET 8.

To install the package use the .NET CLI:

dotnet add package EFDM.Core

Usage

You can find working examples in Sample folder (EFDM.Sample.TestConsole).

Quick start

  1. Create domain entities by inheriting from EFDM.Core models (for example, DictIntDeletableEntity).
  2. Create DataQuery classes (inheriting from DictIntDeletableDataQuery or appropriate base) and override ToFilter to build query filters.
  3. Implement domain services by inheriting DomainServiceBase and injecting IRepository<T, TKey>.
  4. If you need auditing, create AuditSettings and pass them to your DbContext constructor and override InitAuditMapping.

Tips

  • Use dotnet CLI to add the package and to run sample projects.
  • Keep audit IncludedTypes and Ignored/OnlyIncluded properties small for better performance.
  • Use Includes on queries to eager-load navigation properties when required.

Base entities

Inherit your entities from EFDM.Core.Models.Domain (or appropriate base types):

public class Group : DictIntDeletableEntity
{
    public int TypeId { get; set; }
    public virtual GroupType Type { get; set; }
    public virtual ICollection<GroupUser> Users { get; set; }
}

Query entities

Example of a DataQuery with ToFilter override:

public class GroupQuery : DictIntDeletableDataQuery<Group>
{
    public int[] UserIds { get; set; }
    public int[] TypeIds { get; set; }

    public override IQueryFilter<Group> ToFilter() {
        var and = new QueryFilter<Group>();

        if (UserIds?.Any() == true)
            and.Add(x => x.Users.Any(xx => UserIds.Contains(xx.UserId)));

        if (TypeIds?.Any() == true)
            and.Add(x => TypeIds.Contains(x.TypeId));

        return base.ToFilter().Add(and);
    }
}

Domain entity service

Create domain service class for entity by inheriting DomainServiceBase:

public class GroupService : DomainServiceBase<Group, GroupQuery, int, IRepository<Group, int>>, IGroupService
{
    readonly IRepository<User, int> UserRepo;

    public GroupService(
        IRepository<User, int> userRepo,
        IRepository<Group, int> repository,
        ILogger logger
    ) : base(repository, logger)
    {
        UserRepo = userRepo ?? throw new ArgumentNullException(nameof(userRepo));
    }

    public async Task AddUser(int groupId, int userId, CancellationToken cancellationToken = default)
    {
        Group group = await GetByIdAsync(groupId, false, null, cancellationToken);

        User user = (await UserRepo.FetchAsync(new UserQuery
        {
            Ids = new[] { userId },
            IsDeleted = false,
            Includes = new[] { nameof(User.Groups) },
            Take = 1
        }, true, cancellationToken)).First();

        if (user.Groups.Any(e => e.GroupId == groupId))
            return;

        user.Groups.Add(new GroupUser { GroupId = groupId, UserId = userId });
        await UserRepo.SaveAsync(user, cancellationToken);
    }

    public async Task RemoveUser(int groupId, int userId, CancellationToken cancellationToken = default)
    {
        Group group = await GetByIdAsync(groupId, false, null, cancellationToken);

        User user = (await UserRepo.FetchAsync(new UserQuery
        {
            Ids = new[] { userId },
            Includes = new[] { nameof(User.Groups) },
            Take = 1
        }, false, cancellationToken)).FirstOrDefault();

        GroupUser groupUser = user?.Groups.FirstOrDefault(g => g.GroupId == groupId);
        if (groupUser == null)
            return;

        user.Groups.Remove(groupUser);
        await UserRepo.SaveAsync(user, cancellationToken);
    }
}

Database context

Create your DbContext inheriting from EFDM.Core.DAL.Providers.EFDMDatabaseContext. Example:

public class TestDatabaseContext : EFDMDatabaseContext
{
    #region fields & properties

    public override int ExecutorId { get; protected set; } = UserValues.SystemId;

    #region dbsets

    public DbSet<User> Users { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<GroupUser> GroupUsers { get; set; }

    #endregion dbsets

    #endregion fields & properties

    #region constructors

    public TestDatabaseContext(DbContextOptions<TestDatabaseContext> options,
        ILoggerFactory factory = null, IAuditSettings auditSettings = null,
        Action<ModelConfigurationBuilder> conventionsAction = null)
        : base(options, factory, auditSettings, conventionsAction)
    {
    }

    public TestDatabaseContext(string connectionString, IAuditSettings auditSettings = null,
        Action<ModelConfigurationBuilder> conventionsAction = null)
        : base(connectionString, auditSettings, conventionsAction)
    {
    }

    #endregion constructors

    #region context config

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ApplyConfigurationsFromAssembly(Assembly.GetAssembly(GetType()));

        foreach (var entityType in builder.Model.GetEntityTypes())
        {
            builder.ApplyConfiguration<IAuditableUserEntity>(typeof(AuditableUserEntityConfig<>), entityType.ClrType);
        }
    }

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        if (ConventionsAction != null)
            ConventionsAction(configurationBuilder);
    }

    #endregion context config

    #region audit config

    public override void InitAuditMapping()
    {
        // see below
    }

    #endregion audit config
}

Audit entities creation in database context

Configure audit entities creation in your DbContext by overriding InitAuditMapping. Example mapping and common action:

public override void InitAuditMapping()
{
    Auditor.Map<GroupUser, AuditGroupEvent, AuditGroupProperty>(
        (auditEvent, entry, eventEntity) =>
        {
            eventEntity.ObjectId = entry.GetEntry().Entity.GetPropValue($"{nameof(GroupUser.GroupId)}").ToString();
        }
    );
    Auditor.Map<Group, AuditGroupEvent, AuditGroupProperty>(
        (auditEvent, entry, eventEntity) =>
        {
            eventEntity.ObjectId = entry.GetEntry().Entity.GetPropValue("Id").ToString();
        }
    );
    Auditor.Map<TaskAnswer, AuditTaskAnswerEvent, AuditTaskAnswerProperty>(
        (auditEvent, entry, eventEntity) =>
        {
            eventEntity.ObjectId = entry.GetEntry().Entity.GetPropValue("Id").ToString();
        }
    );
    Auditor.SetEventCommonAction<IAuditEventBase<long>>(async (auditEvent, entry, eventEntity) =>
    {
        eventEntity.ActionId = entry.Action;
        eventEntity.CreatedById = ExecutorId;
        eventEntity.ObjectType = entry.EntityType.Name;
        eventEntity.Created = DateTimeOffset.Now;

        await AddAsync(eventEntity);
        await BaseSaveChangesAsync();

        Func<IAuditPropertyBase<long, long>> createPropertyEntity = () =>
        {
            var res = Activator.CreateInstance(Auditor.GetPropertyType(entry.EntityType)) as IAuditPropertyBase<long, long>;
            res.AuditId = eventEntity.Id;
            return res;
        };
        switch (entry.Action)
        {
            case AuditStateActionVals.Insert:
                foreach (var columnVal in entry.ColumnValues)
                {
                    var propertyEntity = createPropertyEntity();
                    propertyEntity.Name = columnVal.Key;
                    propertyEntity.NewValue = Convert.ToString(columnVal.Value);
                    if (!string.IsNullOrEmpty(propertyEntity.Name))
                    {
                        await AddAsync(propertyEntity);
                        await BaseSaveChangesAsync();
                    }
                }
                break;
            case AuditStateActionVals.Delete:
                foreach (var columnVal in entry.ColumnValues)
                {
                    var propertyEntity = createPropertyEntity();
                    propertyEntity.Name = columnVal.Key;
                    propertyEntity.OldValue = Convert.ToString(columnVal.Value);
                    if (!string.IsNullOrEmpty(propertyEntity.Name))
                    {
                        await AddAsync(propertyEntity);
                        await BaseSaveChangesAsync();
                    }
                }
                break;
            case AuditStateActionVals.Update:
                foreach (var change in entry.Changes)
                {
                    var propertyEntity = createPropertyEntity();
                    propertyEntity.Name = change.ColumnName;
                    propertyEntity.NewValue = Convert.ToString(change.NewValue);
                    propertyEntity.OldValue = Convert.ToString(change.OriginalValue);
                    if (!string.IsNullOrEmpty(propertyEntity.Name))
                    {
                        await AddAsync(propertyEntity);
                        await BaseSaveChangesAsync();
                    }
                }
                break;
            default:
                break;
        }
    });
}

Configure database audit for entities & properties

On DbContext creation configure AuditSettings and pass them to the context. Example:

var auditSettings = new AuditSettings()
{
    Enabled = true,
    IncludedTypes = new ConcurrentDictionary<Type, byte>()
    {
        [typeof(Group)] = 1,
        [typeof(GroupUser)] = 1,
        [typeof(TaskAnswer)] = 1
    },
    ExcludedTypeStateActions = new ConcurrentDictionary<Type, List<int>>()
    {
        [typeof(Group)] = new List<int>() { AuditStateActionVals.Insert }
    },
    IgnoredTypeProperties = new ConcurrentDictionary<Type, HashSet<string>>(),
    OnlyIncludedTypeProperties = new ConcurrentDictionary<Type, HashSet<string>>()
};
auditSettings.IgnoredTypeProperties.TryAdd(typeof(Group), new HashSet<string>()
{
    $"{nameof(Group.TextField1)}"
});
auditSettings.OnlyIncludedTypeProperties.TryAdd(typeof(TaskAnswer), new HashSet<string>() {
    $"{nameof(TaskAnswer.TextField1)}"
});

services.AddScoped(provider => new TestDatabaseContext(
    GetDbOptions(provider, configuration), provider.GetService<ILoggerFactory>(), auditSettings)
);
services.AddScoped<EFDMDatabaseContext>(sp => sp.GetRequiredService<TestDatabaseContext>());

RegisterLookupResolver

When auditing navigation properties (foreign keys), EFDM resolves related entities to a human-readable string. By default it uses Id and Title properties (e.g. "42: Admin"). Use RegisterLookupResolver in InitAuditMapping to override this for a specific entity type:

public override void InitAuditMapping()
{
    // Override how User entities are displayed in audit property values
    Auditor.RegisterLookupResolver<User>(user => $"{user.Id}: {user.LastName} {user.FirstName}");

    // Or using the non-generic overload
    Auditor.RegisterLookupResolver(typeof(Group), obj =>
    {
        var group = (Group)obj;
        return $"{group.Id}: {group.Name}";
    });

    // ... rest of mapping
}

The registered resolver takes precedence over the default reflection-based resolver. If the resolver throws, EFDM falls back to the default behavior.

Examples

You can find examples in the Sample folder (EFDM.Sample.TestConsole) and tests in the Test folder (EFDM.Test.* projects).

About

entity framework data manager

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages