简体   繁体   中英

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

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.

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);
}

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