简体   繁体   中英

.net core default value when saving but identity info is different dbcontext

On all my database tables i want to store the userid in a field called CreatedBy. I have a property on a base entity class for this. My db context class currently looks like this:

namespace Infrastructure.Data
{
    public class ManagementContext : DbContext
    {
        public ManagementContext(DbContextOptions<ManagementContext> options)
            : base(options)
        {
        }

        public DbSet<Department> Department { get; set; }        

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSucess, CancellationToken cancellationToken = default(CancellationToken))
        {
            var AddedEntities = ChangeTracker.Entries().Where(E => E.State == EntityState.Added).ToList();

            AddedEntities.ForEach(E =>
            {
                E.Property("CreatedOn").CurrentValue = DateTime.UtcNow;
              //E.Property("CreatedBy").CurrentValue = ????
            });

            var EditedEntities = ChangeTracker.Entries().Where(E => E.State == EntityState.Modified).ToList();
            EditedEntities.ForEach(E =>
            {
                E.Property("LastModifiedOn").CurrentValue = DateTime.UtcNow;
            });
            return base.SaveChangesAsync(acceptAllChangesOnSucess, cancellationToken);
        }
    }
}

My identity user / info is in a different context (as seen in the ewebshop demo) How would i go about setting the value of CreatedBy? Should this be done elsewhere?

Based on the comment on your post, the CreatedBy column value always gets its value from the connected user so you need to do these steps:

Firstly, you need to configure the DI about how to get the current connected user like below into your ConfigureServices of Startup class:

services.AddScoped<IPrincipal>(
    provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

Secondly, inject an instance of IPrincipal into your DbContext like below:

public ManagementContext(DbContextOptions<ManagementContext> options, IPrincipal principal)
    : base(options)
{
    this.principal = principal;
}

Finally when setting the value of CreatedBy column you get the current user by finding it from the value of this.principal.Identity.Name .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM