实体框架代码第一个外键列名继承

时间:2015-03-03 15:48:24

标签: ef-code-first

实体框架代码优先(v6)在数据库中创建一个我不喜欢的列名。在tablename SharepointMappings中,它添加了columnname:' SharepointDestination_DestinationId' (外键)。 它还会生成一个名称SharepointDestinationId。 我希望有一列,一个外键,名称为' SharepointDestinationId'。

我的模型看起来像这样:

public class Destination
{
    public int DestinationId { get; set; }
}

public class SharepointDestination : Destination
{
    public string UserName { get; set; }

    public string Password { get; set; }

    public string Domain { get; set; }

    public string SiteUrl { get; set; }

    public string DocumentLibraryName { get; set; }

    public List<SharepointMapping> Mappings { get; set; }
}

public class SharepointMapping
{
    public int SharepointMappingId { get; set; }

    public string SourceFieldName { get; set; }
    public string DestinationFieldName { get; set; }

    //[ForeignKey("SharepointDestination")]
    public int SharepointDestinationId { get; set; }

    //[ForeignKey("SharepointDestinationId")]
    public virtual SharepointDestination SharepointDestination { get; set; }
}
//.....
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // To use TPT inheritence
    modelBuilder.Entity<SharepointDestination>().ToTable("SharepointDestinations");

        //modelBuilder.Entity<SharepointMapping>()
        //    .HasRequired(m => m.SharepointDestination)
        //    .WithMany(d => d.Mappings)
        //    .HasForeignKey(m => m.SharepointDestinationId)
        //    .WillCascadeOnDelete(true);
}

如果我离开或添加属性ForeignKey并不重要,如果我将属性设为虚拟也无关紧要。完全删除SharepointMapping上的两个属性或给它们一个完整的其他名称没有任何后果。 我认为这与继承结构有关。因为它只是&#39; 1-n映射。

如何配置EF只有1列名称为&#39; SharepointDestinationId&#39;哪个应该是外键? (并且还在SharepointMapping类上具有navigation属性和DestinationId属性)

2 个答案:

答案 0 :(得分:0)

由于SharepointDestination的键是DestinationId,因此EF无法自动识别它。你可以使用注释:

[ForeignKey("DestinationId")]
public virtual SharepointDestination SharepointDestination { get; set; }

并删除此内容:

[ForeignKey("SharepointDestination")]
public int SharepointDestinationId { get; set; }

如果您注释掉注释,流利也应该有效:

    modelBuilder.Entity<SharepointMapping>()
        .HasRequired(m => m.SharepointDestination)
        .WithMany(d => d.Mappings)
        .HasForeignKey(m => m.DestinationId)
        .WillCascadeOnDelete(true);

答案 1 :(得分:0)

ForeignKey属性需要一个属性名称,而不是表列名。

真的,你应该能够做到这一点,没有任何属性。

以下内容应该有效:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; } 

    public virtual Parent Parent { get; set; }
    public int ParentId { get; set; }
}