首页 > 解决方案 > 在实体框架中使用 UserName 作为外键创建 ApplicationUser 导航属性

问题描述

我的实体上有一个 CreatedBy 字段,其中存储了登录用户的用户名。我也想在实体上创建一个导航属性。

我的实体的属性如下所示:

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

如何使 CreatedByUser 导航属性真正起作用。我希望在我的查询中使用“包含”时自动检索它,以便我可以访问:

Product.CreatedByUser.FirstName 和 Product.CreatedByUser.LastName。

我知道如果我选择在 CreatedBy 字段中存储 UserId 而不是 UserName,这将很容易工作,但大多数人将 UserName 存储在 CreatedBy 字段中,因为它很容易通过 Current HttpContext 访问。为了在数据库中清晰起见,我也想保持这种方式,而不是拥有一堆指南。

标签: c#asp.netentity-frameworkasp.net-coreentity-framework-core

解决方案


是的!您可以通过使用 Entity Framework Core备用键功能来执行此操作,如下所示:

您的实体:

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

    public string CreatedBy { get; set; }

    public ApplicationUser CreatedByUser { get; set; } 
}

然后在模型配置中:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<YourEntity>()
        .HasOne(e => e.CreatedByUser)
        .WithMany()
        .HasForeignKey(e => e.CreatedBy)
        .HasPrincipalKey(cu => cu.UserName);
}

推荐阅读