我已經使用EF6生成了幾個類(代碼優先於現有的SQL Server 2012數據庫)。我試圖重命名自動生成的屬性以遵守一些命名約定,例如從record_number
到Number
。然後使用ColumnAttribute
來提供映射。在代碼優先的EF類中重命名外鍵屬性會導致異常
從我的觀察中可以看出,只要我不重命名SQL Server數據庫中的外鍵屬性。例如,在下面的情況下,如果我重命名或者record_store_id
或record_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_id
在internal_stores
表(映射到Store
類)和一個record_pool_id
PK是在internal_pools
表(映射到Pool
類)一個PK。
我該如何得到這個工作?