2014-09-30 22 views
0

我已經使用EF6生成了幾個類(代碼優先於現有的SQL Server 2012數據庫)。我試圖重命名自動生成的屬性以遵守一些命名約定,例如從record_numberNumber。然後使用ColumnAttribute來提供映射。在代碼優先的EF類中重命名外鍵屬性會​​導致異常

從我的觀察中可以看出,只要我不重命名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表(映射到Store類)和一個record_pool_id PK是在internal_pools表(映射到Pool類)一個PK。

我該如何得到這個工作?

回答

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 })