2015-06-27 88 views
1

我創建了一種視圖模型,它具有對實體類型的引用。如何防止實體框架將類映射到數據庫表

這裏是我的視圖模型:

namespace SuperMart.Areas.Admin.ViewModels 
{ 
    [NotMapped] 
    public class ProductDetailVM 
    { 
     public int ProductID { get; set; } 
     [Display(Name = "Name")] 
     public string ProductName { get; set; } 
     [Display(Name = "Price")] 
     public double Price { get; set; } 
     [Display(Name = "Description")] 
     public string Description { get; set; } 

     [Display(Name = "Sub Category")] 
     public string SubCat { get; set; } 

     [Display(Name = "Category")] 
     public string Category { get; set; } 

     [Display(Name = "Status")] 
     public bool Available { get; set; } 

     [Display(Name = "Date Created")] 
     public DateTime? DateCreated { get; set; } 
     public virtual ICollection<ProductImages> ProductImages { get; set; } 
    } 
} 

由視圖模型引用的實體類型:

namespace SuperMart.Entities 
{ 
    public class ProductImages 
    { 
     [Key] 
     public int ImageID { get; set; } 

     public byte[] ImageContent { get; set; } 
     public string ImageContentType { get; set; } 
     public string ImageName { get; set; } 
     public FileType FileType { get; set; } 

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

     public virtual Product Product { get; set; } 
    } 
} 

我打上[NotMapped]屬性的類地說,我不希望它是一個數據庫表,因爲它只是一個視圖模型而不是實體類型。但是,當我運行add-migration命令時,EF仍然試圖將其創建爲表,然後導致外鍵衝突。我也嘗試了modelBuilder.Ignore,但是有一種方法或其他EF似乎忽略了該代碼,因爲它仍然將表創建爲如下所示的表格。

public override void Up() 
{ 
    CreateTable(
       "dbo.ProductDetailVMs", 
       c => new 
        { 
         ProductID = c.Int(nullable: false, identity: true), 
         ProductName = c.String(), 
         Price = c.Double(nullable: false), 
         Description = c.String(), 
         SubCat = c.String(), 
         Category = c.String(), 
         Available = c.Boolean(nullable: false), 
         DateCreated = c.DateTime(), 
        }) 
       .PrimaryKey(t => t.ProductID); 

      AddForeignKey("dbo.ProductImages", "ProductID", "dbo.ProductDetailVMs", "ProductID", cascadeDelete: true); 
     } 
+0

請向我們展示有問題的ViewModel類。 – Marco

+0

@Serv我用我的代碼更新了這個問題 – ibnhamza

+0

你的'DbContext'包含哪些實體?通常,爲了映射實體,您需要在'DbContext'中包含'DbSet '屬性。 –

回答

1

通常情況下,映射你需要包括在一個的DbContext財產DbSet的實體。 - 馬丁Liversage

好吧,事實證明我有點在腿上開槍自殺。我發現那個類出現在我的DbContext類中,因此映射問題。但我必須認真承認我不知道它是如何到達那裏的。反正問題解決了。

+0

也發生在我身上。我右鍵單擊ActionResult添加一個視圖,並選擇一個模板,該自動添加相關的類到DbContext。 – bets