2
我在現有的SQL數據庫上使用EF 4.2 Code First時遇到問題。EF代碼優先,靜態複合外鍵部分
我有多個實體等企業,用戶等
通用信息被存儲在稱爲實體與主密鑰[ENTITYID,EntityTypeId]一個seprate表。
- ENTITYID對應於CorporateId,用戶ID等
- EntityTypeId是靜態ID,用於像discrimiator實體
我有下面的類設計之間。
public class User
{
public int Id {get;set;}
public int EntityTypeId { get { return 1; } set { }}
public Entity Entity {get;set;}
}
public class Entity
{
public int Id {get;set;}
public int EntityTypeId {get;set;}
}
正如您所見,EntityTypeId是靜態屬性,並且用戶表中沒有對應的列。
地圖:
public UserMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Table & Column Mappings
this.ToTable("User");
this.Property(t => t.Id).HasColumnName("UserId");
// Relationships
this.HasRequired(t => t.Entity)
.WithMany()
.HasForeignKey(p => new { p.Id, p.EntityTypeId }); //<-- Problem
}
public EntityMap()
{
// Primary Key
this.HasKey(t => new { t.Id, t.EntityTypeId });
// Table & Column Mappings
this.ToTable("Entity");
this.Property(t => t.Id).HasColumnName("EntityId");
this.Property(t => t.EntityTypeId).HasColumnName("EntityTypeId");
}
當我運行這段代碼,我得到的錯誤: System.Data.SqlClient.SqlException:無效的列名稱EntityTypeId「。
我認爲這是因爲EntityTypeId列在用戶表中不存在。 有沒有解決這個問題的方法,因爲我無法在表格上創建此列?!
非常感謝