代码之家  ›  专栏  ›  技术社区  ›  Blake Rivell

在实体框架中使用用户名作为外键创建ApplicationUser导航属性

  •  0
  • Blake Rivell  · 技术社区  · 7 年前

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

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

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

    如何使CreatedByUser导航属性实际工作。我希望在查询中使用“Include”时自动检索它,以便访问:

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

    我知道如果我选择在CreatedBy字段中存储UserId而不是UserName,这将很容易实现,但是大多数人将UserName存储在CreatedBy字段中,因为它很容易通过当前HttpContext进行访问。为了在数据库中保持清晰,我也希望保持这种方式,而不是使用一堆guid。

    1 回复  |  直到 7 年前
        1
  •  0
  •   TanvirArjel    7 年前

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