在代码中重命名外键属性第一个EF类会导致异常

时间:2014-09-30 12:03:21

标签: c# .net entity-framework entity-framework-6

我使用EF6生成了几个类(首先是代码到现有的SQL Server 2012数据库)。我尝试重命名自动生成的属性以遵守某些命名约定,例如从record_numberNumber。然后使用ColumnAttribute来提供映射。

根据我的观察,只要我没有在SQL Server数据库中重命名属于外键的属性,这就有效。例如,在下列情况下,如果我重命名record_store_idrecord_pool_id - 两者都是FK列 - 会抛出异常:

[Table("internal_records")]
public partial class Record
{
    [Key]
    [Column("record_number", Order = 0)]
    public long Number { get; set; }

    [Key]
    [Column("collection_id", Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CollectionId { get; set; }

    public short record_store_id { get; set; } // Exception if I rename this to e.g. RecordStoreId and add Column("record_store_id")

    [Required]
    [MaxLength(255)]    
    public byte[] record_pool_id { get; set; } // Exception if I rename this to e.g. RecordStoreId and add Column("record_store_id")

    ... // some other properties (not problematic)

    public virtual Collection InternalCollection { get; set; }
    public virtual Pool InternalPool { get; set; }
}

即。如果我使用:

[Column("record_store_id")]
public short RecordStoreId { get; set; }

[Required]
[Column("record_pool_id")]
[MaxLength(255)]    
public byte[] RecordPoolId { get; set; }

使用Linq查询时会抛出异常:

Unhandled Exception: System.InvalidOperationException: The properties expression 'e => new <>f__AnonymousType0`2(record_store_id = e.RecordStoreId, record_pool_id = e.RecordPoolId)' is not valid. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.
   at System.Data.Entity.ModelConfiguration.Configuration.DependentNavigationPropertyConfiguration`1.HasForeignKey[TKey](Expression`1 foreignKeyExpression)

我尝试使用ForeignKeyAttribute,但我必须做错了,因为这并没有解决我的问题。

record_store_idinternal_stores表中的PK(映射到Store类),record_pool_idinternal_pools表中的PK(映射到{{1} })。)。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

当我重命名一个属性时,问题就在于OnModelCreating()被更新的方式。最初,代码是:

modelBuilder.Entity<InternalPool>()
    .HasMany(e => e.internal_records)
    .WithRequired(e => e.InternalPool)
    .HasForeignKey(e => new { e.record_store_id, e.record_pool_id })
    .WillCascadeOnDelete(false);

重命名(通过VS重构),例如record_store_idRecordStoreId将第4行更改为:

.HasForeignKey(e => new { RecordStoreId = e.record_store_id, e.store_pool_id })

我必须手动更改此值以反映我重命名的值,即RecordStoreIdRecordPoolId

.HasForeignKey(e => new { e.RecordStoreId, e.RecordPoolId })