![](/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.