如何自动将外键 属性 映射到 EF6 中的数据库

How to map foreign key property to database in EF6 automatically

在我的数据库中有两个表:

场景:

Id
Name
Location_Id

地点

Id
Name

所以 Scenario 有一个指向 Locations.

的外键

在我的代码中:

Scenario.cs:

public int Id { get; set; }
public string Name { get; set; }
public int LocationId { get; set; }

Location.cs

public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Screen> Screens { get; set; } // I do not really need this...

当我这样使用它时出现异常:

SqlException: Invalid column name 'LocationId'

但是,当我在 Scenario class 中使用 public virtual Location { get; set; } 时,它当然会识别这种关系。

我想要的是 EF 自动 'maps' LocationIdLocation_Id。我不想在我的数据库中使用 LocationId,因为其他外键正在使用下划线:Entity_Id。所以我不想像这样配置每个外键:

modelBuilder.Entity<Scenario>().Property(s => s.LocationId).HasColumnName("Location_Id");

使用数据属性ForeignKey:

public int Id { get; set; }
public string Name { get; set; }
public Location Location { get; set; }
[ForeignKey("Location")]
public int LocationId { get; set; }

用流利的API,看起来差不多。省略数据属性并包含此代码:

modelBuilder.Entity<Scenarios>()
    .HasOne<Location>(s => s.Location)
    .WithMany()
    .HasForeignKey(s => s.LocationId);

您可以使用 custom code first conventions.

这是一种查找以 Id 结尾且至少有一个字符在 Id 之前的属性的约定。约定将名称替换为 <preceding part> + _ + Id.

using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Text.RegularExpressions;
...
class ForeignKeyPropertyConvention : IStoreModelConvention<EdmProperty>
{
    public void Apply(EdmProperty property, DbModel model)
    {
        property.Name = Regex.Replace(property.Name, "^(.*.)(Id)$", @"_");
    }
}

将此约定添加到 OnModelCreating 中的模型构建器:

modelBuilder.Conventions.Add(new ForeignKeyPropertyConvention());

当然,对于一个外键 属性 这有点过分了,但在较大的项目中,这将是一种方便的方法。

仅此一个 属性 添加此行就足够了:

modelBuilder.Entity<Scenario>().Property(s => s.LocationId)
    .HasColumnName("Location_Id");