首页 > 解决方案 > EF6 数据库优先:在没有外键约束的实体之间添加关系

问题描述

在我们当前的项目中,我们的团队使用 EntityFramework 6 和数据库优先方法。由于应用程序应该使用什么,数据库不使用外键约束。是否还有办法让 EntityFramework 自动将外键映射到其他实体?

这是一个示例,现在我的系统模型如下所示:

public partial class System
{
    public int SystemID { get; set; }
    public string SystemName { get; set; }
    public int UserID { get; set; }
}

使用外键约束,它应该如下所示:

public partial class System
{
    public int SystemID { get; set; }
    public string SystemName { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
}

有没有办法自动执行此操作或将其编码到 DbContext 中,这样我每次想要访问一个连接的实体时都不必手动进行映射?

标签: c#entity-frameworkentity-framework-6

解决方案


DbContext无论实际数据库中是否存在外键,您都可以使用所需的关系配置您的关系。

System例如,以下代码段将配置和之间的一对多关系User

public class ExampleDbContext : DbContext
{
  public ExampleDbContext() : base("connstr") {}

  public DbSet<System> Systems { get; set; }
  public DbSet<User> Users { get; set; }
  
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<System>()
      .HasRequired(s => s.User)
      .WithMany(u => u.Systems)
      .HasForeignKey(s => s.UserId);
  }
}

阅读有关EF6 文档的更多信息。


推荐阅读