【问题标题】:Update Entity to expose existing foreign key property in EF code first?更新实体以首先在 EF 代码中公开现有的外键属性?
【发布时间】:2016-02-24 19:44:20
【问题描述】:

我试过这个问题: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 自动生成的不匹配。在我的 POCO 中,没有一个其他 FK 属性使用下划线。但这就是数据库中的列名。

【问题讨论】:

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


    【解决方案1】:

    可以通过数据注释轻松完成:

    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
    }
    

    Fluent API 怎么样,看来实现目标的唯一方法就是模仿上面的方法:

    public class FormReportMapping : EntityTypeConfiguration<FormReport>
    {
        public FormReportMapping()
        {
            Property(x => x.FormEntryId)
                .HasColumnName("FormEntry_Id")
                .HasColumnAnnotation("ForeignKey", "FormEntry");
            // ...
        }
    }
    

    【讨论】:

    • 有什么方法可以使用流畅的 API 吗?我们实际上并没有做任何属性,我们所有的映射都在上面的单独的类中。在这种情况下只使用属性来做这将是糟糕的设计。从我所看到的所有其他方面来看,这些属性都有一些流畅的 API 推论,但无法弄清楚这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2016-01-31
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多