更新实体首先在EF代码中公开现有的外键属性?

时间:2016-02-24 19:44:21

标签: c# .net entity-framework ef-code-first

我尝试了这个问题:How to expose Foreign Key property to existing entity having navigational property using 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中使用下划线。但这就是数据库中的列名称。

1 个答案:

答案 0 :(得分:2)

可以使用数据注释轻松完成:

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");
        // ...
    }
}