2012-03-18 61 views
1

我正在學習針對northwind數據庫的EF4.1。我創建了一個POCO類像這樣故意用非相同的列名,並沒有在該方案中存在的屬性,所以我可以學習,準備映射來更新我的遺留應用程序:在EF4.1中使用POCO映射FluentAPI

public class Product 
    { 
     public int ProductID { get; set; } 
     public string ProductName { get; set; } 
     public Decimal? UnitPrice { get; set; } 
     public bool Discontinued { get; set; } 
     public Int16 QuantityInStock { get; set; } 
     public int CategoryID { get; set; } 
     public Category Category { get; set; } 
    } 

我要地圖我架構這個實體是這樣的:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Product>().Map(config => 
     { 
      config.Properties(p => new 
      { 
       p.ProductName, 
       p.ProductID, 
       p.CategoryID, 
       p.Discontinued, 
       p.UnitPrice 
      }); 
     }); 
    modelBuilder.Entity<Product>().ToTable("Products"); 
    base.OnModelCreating(modelBuilder); 
} 

奇怪的是,當我試試這個:

Product tmp = db.Products.Find(4); 

我得到這個例外,我不知道爲什麼,因爲我所說的,我甚至映射它ToTable( 「產品」): {"Invalid object name 'dbo.Product1'."}

這究竟是爲什麼?

回答

1

隨着modelBuilder.Entity<Product>().Map您使用的代碼首先一個比較先進的映射選項稱爲表拆分。您的映射表示您已在Properties(p => new...)中列出的實體Product的屬性應該映射到另一個表,而不是其他屬性。其他屬性如Products所示,如您在ToTable調用中定義的那樣。對於其他屬性,您根本沒有指定表名(在Map(config => config.ToTable(...) ...操作中應爲ToTable)。我的猜測是,EF假定某種默認表名Product1顯然不存在。

我不確定是否真的想將實體拆分爲兩個不同的表。讀你的第一個句子......

...不相同的列名,並沒有在 方案存在屬性...

...我想你需要的主要以下兩個映射選項:

屬性在模型類,而不在數據庫中相應的列沒有被映射屬性:

modelBuilder.Entity<Product>().Ignore(p => p.QuantityInStock); 

隨着數據註釋:

[NotMapped] 
public Int16 QuantityInStock { get; set; } 

,您可以通過屬性名稱映射到另一個列名:

modelBuilder.Entity<Product>().Property(p => p.Discontinued) 
    .HasColumnName("MyOtherColumnName"); 

隨着數據註釋:

[Column("MyOtherColumnName")] 
public bool Discontinued { get; set; } 
+0

感謝。我發現這個Ignore選項,但每次我添加一個屬性到我的類時,我必須更新地圖忽略它,這是一個痛苦。更糟的是,我有現有的商業類,我想要使用有很多屬性,並會很痛苦,忽略每一個。有什麼辦法可以指定應該設置哪些屬性而不是忽略哪些屬性? – powlette 2012-03-18 21:26:28

+0

@powlette:不,我不知道。 – Slauma 2012-03-18 21:30:27

+0

這是之前問過的:http://stackoverflow.com/questions/9585263/use-entity-frameworks-structuraltypeconfiguration-ignore-to-ignore-all-proper – 2012-03-18 21:38:12