Search code examples
c#entity-frameworkasp.net-identity

Identity Framework 2 does not apply changes on new custom entity


I'm new to Identity Framework and maybe what I'm doing here is not the best approach, but either way, here is my scenario:

Beside the "Role" factor, some areas on my application should consider also if a given user is attached to a given "Company".

I created a new entity "Company" (very simple, only with Id and Name) and a relationship entity "UserCompany" (with the user and the company's Id). I tried to make it as similar as possible with the structure used between Roles and Users on Identity Framework.

In my ApplicationDbContext I added both DbSets and some logic for, for example, adding a list of companies to a user.

The problem that I'm facing is that "SaveChanges" does not apply the changes to the database. *Edit: no error is thrown and the result of SaveChanges() is "1".

Here is a sample code from my ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Company> Companies { get; set; }

    public DbSet<UserCompany> UserCompanies { get; set; }

    //constructors, etc...

    public void AddToCompanies(string _userId, params string[] _companyIds)
    {
        foreach (var companyId in _companyIds)
        {
            UserCompanies.Add(new UserCompany()
            {
                UserId = _userId,
                DataAreaId = companyId
            });
        }

        int result = this.SaveChanges();

    }

}

And here is how I mapped this "UserCompany" entity

 public class UserCompany
{
    [Key, Column(Order = 1), ForeignKey("ApplicationUser")]
    public string UserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    [Key, Column(Order = 2), ForeignKey("Company")]
    public string DataAreaId { get; set; }
    public virtual Company Company { get; set; }
}

On my UserAdminController class I created a private ApplicationDbContext object that is responsible for calling this logic. I suspect there is some problem in the way I'm dealing with two diferent contexts to save this data (one inside the ApplicationUserManager object and this new one), but I'm not sure if this is really the problem or if I'm missing something else here.

Any help would be appreciated!


Solution

  • Is the UserCompany model supposed to be like this

    public class UserCompany
    {
       [Key, Column(Order = 1)]
       public string UserId { get; set; }
    
       [ForeignKey("UserId ")]
       public virtual ApplicationUser ApplicationUser { get; set; }
    
       [Key, Column(Order = 2)]
       public string DataAreaId { get; set; }
    
       [ForeignKey("DataAreaId")]
       public virtual Company Company { get; set; }
    }
    

    And check if you use TransactionScope and not commit it. Hope it helps!