我是MVC3和Web開發中的完整初學者。(MVC3/Entity Framework)如何在使用候選鍵作爲外鍵的數據庫中執行CRUD操作
我的客戶端數據庫使用一個表的唯一候選鍵作爲另一個表的外鍵。我無法改變數據庫的設計方式。我有從數據庫表派生的模型。我知道實體框架不支持候選鍵作爲另一個表的外鍵。
所以我的問題是,專業人員如何解決實體框架的這種限制?
我是MVC3和Web開發中的完整初學者。(MVC3/Entity Framework)如何在使用候選鍵作爲外鍵的數據庫中執行CRUD操作
我的客戶端數據庫使用一個表的唯一候選鍵作爲另一個表的外鍵。我無法改變數據庫的設計方式。我有從數據庫表派生的模型。我知道實體框架不支持候選鍵作爲另一個表的外鍵。
所以我的問題是,專業人員如何解決實體框架的這種限制?
由於當前版本的EF需要FK指向PK,所以這不是一個容易克服的問題。
我使用的一種技術是(使用EF CodeFirst ... er ... Second)來覆蓋Parent表映射中的PKEY,並指定一個匿名類型。
public class ParentObject
{
public int Id {get; set;} //the actual PKEY in the Db
public string CandidateKey1 {get;set;}
public string CandidateKey2 {get;set;}
public string CandidateKey3 {get;set;}
public virtual ICollection<ChildObject> ChildObjects {get;set;}
}
public class ChildObject
{
public int Id {get; set;}
public string CandidateKey1 {get;set;}
public string CandidateKey2 {get;set;}
public string CandidateKey3 {get;set;}
public virtual ParentObject ParentObject {get;set;}
}
爲了這個工作,你需要指定父表的PKEY是一個匿名的對象,而不是實際PKEY存儲在數據庫中。
public ParentObjectMap()
{
// Primary Key
//this.HasKey(t => t.Id); //override this as PKEY for EF purposes
this.HasKey(t => new { t.CandidateKey1, t.CandidateKey2, t.CandidateKey3 });
// Table & Column Mappings
this.ToTable("ParentTable");
this.Property(t => t.Id).HasColumnName("ParentId");
this.Property(t => t.CandidateKey1).HasColumnName("Key1");
this.Property(t => t.CandidateKey2).HasColumnName("Key2");
this.Property(t => t.CandidateKey3).HasColumnName("Key3");
}
和子對象映射
public ChildObjectMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Table & Column Mappings
this.ToTable("ChildTable");
this.Property(t => t.Id).HasColumnName("ChildId");
this.Property(t => t.CandidateKey1).HasColumnName("Key1");
this.Property(t => t.CandidateKey2).HasColumnName("Key2");
this.Property(t => t.CandidateKey3).HasColumnName("Key3");
this.HasRequired(t => t.ParentObject)
.WithMany(t => t.ChildObjects)
.HasForeignKey(t => new { t.CandidateKey1, t.CandidateKey2, t.CandidateKey3 });
}
當然,這會產生其他問題,如實際父Id屬性,你將需要應對執行代碼的uniqueueness。然而,這種技術已經爲我編寫代碼時針對類似的(候選鍵控)Progress 4GL OpenEdge - > MSSQL數據庫(我無法控制)編寫代碼。
它的速度也不如原生EF-> MSSQL映射那樣利用DB中的FK關係。
截至2011年,微軟正在研究這個問題(「唯一性限制」),但更新的博客文章顯示它已從EF 5推遲。http://blogs.msdn.com/b/efdesign/archive/2011/03/ 09/unique-constraints-in-the-entity-framework.aspx – 2013-04-30 14:54:28
感謝您的回答。我會嘗試的。我最初的工作是將這些表視爲單獨的未連接的表,然後使用AJAX和LINQ使用where子句抽取數據,但我不喜歡這個想法。 – Mikey 2013-04-30 15:25:34
對不起,我忘了提及每個表都有一個主鍵和一個或多個候選鍵。這些候選鍵被相關表用作外鍵。 – Mikey 2013-04-30 13:55:32