c# – Performance in String Filter vs Foreign Key Queries

Question:

I'm working on an Asp.Net MVC 5 project that uses code first and all entities have a property called UserId of type string . When I'm going to make queries filtering by a certain user ( Asp.Net Identity ) I do it like this:

string currentUserId = User.Identity.GetUserId();
var products = await db.Products.Where(_ => _.UserId == currentUserId).ToListAsync();

Am I losing performance because I don't have a foreign key relationship and just store the UserId in a string property?

Answer:

Am I losing performance because I don't have a foreign key relationship and just store the UserId in a string property?

It is. In fact, you can normally associate your ApplicationUser with any other entity, taking only a few precautions.

For the relationship between the entities to work, it is necessary to take care to envelop the context with the RoleManager and the UserManager as follows:

UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

In any case, if you feel that you are experiencing a lot of performance loss, I suggest redeploying your ApplicationUser using a Guid or int key:

public class MeuUserComGuid : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
{
    public User()
    {
        Id = Guid.NewGuid();
    }

    public User(string name) : this() { UserName = name; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Scroll to Top