2012-05-07 78 views
1

我有幾個模型和數據庫,但沒有外鍵將任何東西鏈接在一起。這似乎是我項目中的一個巨大弱點,所以我試圖將外鍵插入到我的模型中,然後可能基於我的模型重新生成我的數據庫。模型上的外鍵(代碼優先)

我在理解外鍵如何工作方面遇到了一些麻煩,特別是在一對多關係中。

對於這個例子,我有一個產品或產品,每個產品可以有多個評論:

我已經刪除了一些註釋和屬性凝聚模型。

產品型號/實體:

public class Product 
    { 
     public int ProductId { get; set; } 

     public int OwnerId {get; set; } 

     public string Title { get; set; } 

     public int Rating { get; set; } 

     public decimal Price { get; set; } 

     public int Quantity { get; set; } 

     public string Description { get; set; } 
    } 

審查模式/實體:

public class Review 
    { 

     public int ReviewId { get; set; } 

     public int ProductId { get; set; } 

     public int WriterId { get; set; } 

     public string Title { get; set; } 

     public string Body { get; set; } 
    } 

我想對產品的產品編號,以審查該產品編號外鍵約束。我將如何完成這項工作?

回答

0

外鍵的目的是將錶鏈接在一起。例如,有一個唯一的身份證號碼時,外鍵很容易解釋。 productId應該是唯一的ID,可能是產品表的主鍵。在評論表中,productId是一個外鍵,因爲它允許表連接並查看來自兩個表的所有類別的數據。

select ProductId,Title,Price,WriterId,Description from Product as P,Review as R where P.ProductId = R.ProductId;

當這個select語句針對urdb運行時,您將在review表中看到產品唯一的id,title,price,writer id,desript。關鍵線路P.ProductId = R.ProductId

還要確保外鍵不爲空

4

至少需要一個導航屬性來定義兩個實體之間的關係,例如:

public class Review 
{ 
    public int ReviewId { get; set; } 

    [ForeignKey("Product")] 
    public int ProductId { get; set; } 
    public Product Product { get; set; } 

    public int WriterId { get; set; } 
    public string Title { get; set; } 
    public string Body { get; set; } 
} 

您還可以在Product添加集合屬性,如果你想:

public ICollection<Review> Reviews { get; set; } 

而不是使用一個[ForeignKey]屬性?

modelBuilder.Entity<Review>() 
    .HasRequired(r => r.Product) 
    .WithMany() // or .WithMany(p => p.Reviews) 
    .HasForeignKey(r => r.ProductId); 
+0

模型構建器的內部OnModelCreating specificed,正確的目前我使用'modelBuilder.Entity ().ToTable( 「評論」,SCHEMANAME: 「MYSCHEMA」),您可以用流利的API定義FK;'我將需要基於我的代碼重新生成我的數據庫,對嗎? – Johannes

+0

@Johannes:是的,在'OnModelCreating'中。您當前的映射僅將實體映射到表名。你可以添加更多的映射代碼,只需重複'modelBuilder.Entity ()....'東西。您不需要*重新生成數據庫,您還可以在數據庫模式和模型中進行「並行」更改,以便匹配和關閉數據庫初始化程序('Database.SetInitializer (null)'),通常如果數據庫正在生產中。如果您處於開發階段,則有助於讓EF重新生成數據庫模式,因爲它確保它與模型匹配。或者您可以使用EF 4.3「遷移」功能。 – Slauma