0

I am using Simple Membership and a UserProfile table that maintains UserId and UserName:

 public partial class UserProfile
    {
        public UserProfile()
        {
            this.webpages_Roles = new List<webpages_Roles>();
        }

        public int UserId { get; set; }
        public string UserName { get; set; }
        public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
    }

With Entity Framework I am running the following which is inside my Context:

 public partial class UowContext : DbContext

    // code to set up DbSets here ...
    public DbSet<Content> Contents { get; set; }

    private void ApplyRules()
    {
        var r1 = new Random();
        var r2 = new Random();

        foreach (var entry in this.ChangeTracker.Entries()
                     .Where(
                          e => e.Entity is IAuditableTable &&
                         (e.State == EntityState.Added) ||
                         (e.State == EntityState.Modified)))
        {
            IAuditableTable e = (IAuditableTable)entry.Entity;
            if (entry.State == EntityState.Added)
            {
                e.CreatedBy = // I want to put the integer value of UserId here
                e.CreatedDate = DateTime.Now;
            }
            e.ModifiedBy = // I want to put the integer value of UserId here
            e.ModifiedDate = DateTime.Now;
        }
    }

Here is the schema showing how user information is stored. Note that I store the integer UserId and not the UserName in the tables:

public abstract class AuditableTable : IAuditableTable
{
    public virtual byte[] Version { get; set; }
    public int CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public int ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
}

Here's an example of a controller action that I use:

public HttpResponseMessage PostContent(Content content)
    {
        try
        {
            _uow.Contents.Add(content);
            _uow.Commit();
            var response = Request.CreateResponse<Content>(HttpStatusCode.Created, content);
            return response;
        }
        catch (DbUpdateException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
        } 
    }

I then have:

public class UowBase : IUow, IDisposable
{
    public UowBase(IRepositoryProvider repositoryProvider)
    {
        CreateDbContext();

        repositoryProvider.DbContext = DbContext;
        RepositoryProvider = repositoryProvider;
    }

    public IRepository<Content> Contents { get { return GetStandardRepo<Content>(); } }

and:

public class GenericRepository<T> : IRepository<T> where T : class
{
    public GenericRepository(DbContext dbContext)
    {
        if (dbContext == null) 
            throw new ArgumentNullException("An instance of DbContext is required to use this repository", "context");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Detached)
        {
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
    }

How can I determine the UserId from inside of my Context so I can populate the Id in my tables?

  • 3
    Check http://stackoverflow.com/questions/7641552/overriding-savechanges-and-setting-modifieddate-but-how-do-i-set-modifiedby/7642041#7642041 – Eranga Jul 09 '13 at 10:08
  • Thanks for the link but that question populates ModifiedBy with name and my database stores the UserId. I will update my question to make it a bit more clear. –  Jul 09 '13 at 10:29
  • Do you mena DbContext? Where are you creating and using the Context? In a Controller Action? How does the invoking code look like? – JotaBe Jul 09 '13 at 11:17
  • Yes the code above is inside: public partial class UowContext : DbContext –  Jul 09 '13 at 11:23
  • Your `UowContext` should have a property 'UserId' and it should be populated in your controller(idealy through DI). – Eranga Jul 10 '13 at 03:08

1 Answers1

0

In Code you will have UserName with you through:

HttpContext.Current.User.Identity.Name

you can than query UserProfile table against that Name and get the UserId from there and than assign it to ModifiedBy attribute.

Make sure that you query UserProfile table outside the foreach loop :)

Imran Balouch
  • 2,170
  • 1
  • 18
  • 37