Creating an ApplicationUser navigation property using UserName as the foreign key in Entity Framework

asp.net asp.net-core c# entity-framework entity-framework-core

Question

I have a CreatedBy field on my entities where the logged in user's UserName is stored. I would like to create a navigation property on the entity as well.

The properties of my entity look like this:

public int Id { get; set; }
public string Name { get; set; }
// public ApplicationUser CreatedByUser { get; set; }
public string CreatedBy { get; set; }

How can I make the CreatedByUser navigation property actually work. I would like it to automatically be retrieved when I use "Include" in my queries so I have access to the:

Product.CreatedByUser.FirstName and Product.CreatedByUser.LastName.

I know this will easily work if I choose to store UserId rather than UserName in the CreatedBy field, but most people store the UserName in a CreatedBy field since it is easy to access through the Current HttpContext. I would also like to keep it this way for clarity in the database, rather than having a bunch of guids.

1
0
12/27/2018 2:59:47 PM

Popular Answer

Yes! You can do this by using Entity Framework Core Alternate Keys feature as follows:

Your Entity:

public class YourEntity
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string CreatedBy { get; set; }

    public ApplicationUser CreatedByUser { get; set; } 
}

Then in the Model Configuration:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<YourEntity>()
        .HasOne(e => e.CreatedByUser)
        .WithMany()
        .HasForeignKey(e => e.CreatedBy)
        .HasPrincipalKey(cu => cu.UserName);
}
0
12/27/2018 4:26:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow