![](/img/trans.png)
[英]How to expose Foreign Key property to existing entity having navigational property using EF6 Code First
[英]Update Entity to expose existing foreign key property in EF code first?
我尝试了以下问题: 如何使用EF6 Code First将外键属性公开给具有导航属性的现有实体 ,但它不起作用。 我收到以下错误:
The index 'IX_FormEntry_Id' is dependent on column 'FormEntry_Id'.
ALTER TABLE ALTER COLUMN FormEntry_Id failed because one or more objects
access this column.
我只是想在FormReport POCO上公开FormEntryId:
public class FormReport : Entity
{
public Guid? FormEntryId { get; set; } //I added this
public virtual FormEntry FormEntry { get; set; }
//other props
}
我使用了上面链接的答案中概述的映射:
public class FormReportMapping : EntityTypeConfiguration<FormReport>
{
public FormReportMapping()
{
HasRequired(x => x.FormEntry)
.WithOptional()
.Map(p => p.MapKey("FormEntry_Id"));
new EntityMap().MapInheritedProperties(this);
}
}
我希望它能识别出这就是原来的样子,不需要任何更改,但是那不是正在发生的事情,我该怎么做?
编辑:我想保留我的命名约定,这与EF自动生成的命名约定不匹配。 我的FK属性中没有其他一个在POCO中使用下划线。 但这就是数据库中的列名。
可以使用数据注释轻松完成:
public class FormReport : Entity
{
[Column("FormEntry_Id")]) // Map to the existing column name
[ForeignKey("FormEntry")] // Associate with the navigation property
public Guid? FormEntryId { get; set; }
public virtual FormEntry FormEntry { get; set; }
//other props
}
流畅的API怎么样,看来实现此目标的唯一方法就是模仿以上内容:
public class FormReportMapping : EntityTypeConfiguration<FormReport>
{
public FormReportMapping()
{
Property(x => x.FormEntryId)
.HasColumnName("FormEntry_Id")
.HasColumnAnnotation("ForeignKey", "FormEntry");
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.