c# - 在实体框架中使用 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 访问。为了在数据库中清晰起见,我也想保持这种方式,而不是拥有一堆指南。
解决方案
是的!您可以通过使用 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);
}
推荐阅读
- amazon-web-services - Elastic Load Balancer 可以自动扩展吗?
- php - 拆分多维数组并分组为关联数组作为php中的相同fileld
- phpexcel - 使用 PHPExcel 的数据透视表
- java - 程序确实在 Eclipse 中发送邮件,但在 jarred 时不发送
- c++ - google-cloud-cpp CMake 生成失败
- php - 在静态方法中调用属性时出错
- android - Gradle TransitiveDependency 版本冲突
- redis - 保持访问配置数据<10 GB 并从 Flink 流应用程序中访问每条记录的最佳分布式缓存?
- android - Firebase 函数 - 获取当前 DataSnapshot 的同级
- c++ - 类内初始化顺序与构造函数初始化列表