![](/img/trans.png)
[英]How to expose Foreign Key property to existing entity having navigational property using EF6 Code First
[英]How to map foreign key property to database in EF6 automatically
在我的数据库中,我有两个表:
场景:
Id
Name
Location_Id
地点:
Id
Name
所以Scenario有一个Locations的外键。
在代码中我有这个:
场景.cs:
public int Id { get; set; }
public string Name { get; set; }
public int LocationId { get; set; }
位置.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:列名“LocationId”无效
但是,当我使用public virtual Location { get; set; }
public virtual Location { get; set; }
在我的Scenario
public virtual Location { get; set; }
中,它当然可以识别这种关系。
我想要的是 EF 自动将LocationId
映射到Location_Id
。 我不希望LocationId
在我的数据库中,因为其他外键正在使用下划线: Entity_Id
。 所以我不想像这样配置每个外键:
modelBuilder.Entity<Scenario>().Property(s => s.LocationId).HasColumnName("Location_Id");
您可以使用自定义代码优先约定。
这是一种查找以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)$", @"$1_$2");
}
}
将此约定添加到 OnModelCreating 中的OnModelCreating
构建器:
modelBuilder.Conventions.Add(new ForeignKeyPropertyConvention());
当然,对于一个外键属性来说,这是多余的,但在较大的项目中,这将是一种方便的方法。
对于这一个属性,添加这一行就足够了:
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,它看起来几乎一样。 省略 data 属性并包含以下代码:
modelBuilder.Entity<Scenarios>()
.HasOne<Location>(s => s.Location)
.WithMany()
.HasForeignKey(s => s.LocationId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.