【问题标题】:Creating an ApplicationUser navigation property using UserName as the foreign key in Entity Framework在实体框架中使用 UserName 作为外键创建 ApplicationUser 导航属性
【发布时间】:2018-12-27 14:50:19
【问题描述】:

我的实体上有一个 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。

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

【问题讨论】:

  • 你能显示实体 ApplicationUser 及其配置吗?
  • @gsharp 这没什么。只是 ASP.NET Core Identity 附带的默认 IdentityUser。我添加了两个附加属性 FirstName 和 LastName。
  • “为了在数据库中清晰起见,我也想保持这种方式,而不是拥有一堆 guid”。实际上恰恰相反——您可以通过在数据库中使用唯一 ID 和 GUID 来获得清晰性,而不使用它们会造成混乱。假设您有 150000 个由用户“user1”创建的产品,现在您需要更改他的用户名。您要更新 Products 表中的 150 000 行吗? :)
  • @BlakeRivell 嗨!,我已经回答了你的问题,但你没有说它是否对你有用?如果您让我知道您的反馈,那就太好了。谢谢。

标签: c# asp.net entity-framework asp.net-core entity-framework-core


【解决方案1】:

是的!您可以通过使用 Entity Framework Core Alternate Keys 功能来做到这一点,如下所示:

您的实体:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多