我創建了一種視圖模型,它具有對實體類型的引用。如何防止實體框架將類映射到數據庫表
這裏是我的視圖模型:
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);
}
請向我們展示有問題的ViewModel類。 – Marco
@Serv我用我的代碼更新了這個問題 – ibnhamza
你的'DbContext'包含哪些實體?通常,爲了映射實體,您需要在'DbContext'中包含'DbSet'屬性。 –