簡體   English   中英

POCO實體框架和多態性

[英]POCO entity framework and polymorphism

我首先使用Entities Framework Code,接下來是POCO類:

 public class Product 
    {       
        public int ProductID { get; set; }
        public int Title{ get; set; }
        public int Price { get; set; }

        public int ProductCategoryID { get; set; }
        public virtual ProductCategory ProductCategory { get; set; }
    }

  public class ProductCategory 
    {
        public int ProductCategoryID { get; set; }        
        public int Title{ get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }

因此,讓產品具有一個簡單的方法MakeSale ,該方法取決於ProductCategory

public int void GiveSale()
{
  //I can do like this ...
    switch (this.ProductCategoryID)
    {
        case 1: return this.Price * 0,8;
        break;
        case 2: return 0;
        ...         
    }
 }

但我不喜歡這種方法,我想使用OOP並具有以下內容:

public class Dress : Product 
{
  public override int void GiveSale()
   {
      return this.Price * 0,8;
   }
}

public class Shoes : Product 
{
  public override int void GiveSale()
   {
      return 0;
   }
}

如何使用Entities Framework做到這一點並保存實體的易用性?

您可以嘗試對對象使用EF繼承。 它也可以在Code First中使用-http: //weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table -per層次結構,tph.aspx

根據您的需求,有3種不同的方法:

  1. 每個層次結構的表-當所有對象都與同一個表相關時
  2. 每個類型的表-當所有類都可以在共享表中擁有公共數據,並且所有特定字段都映射到另一個表時
  3. 每個具體類的表-當所有類都有自己的表時。 在這種情況下,公共數據結構將在每個表中重復

您需要基於OnModelCreating方法中的一些數據來映射您的Dress,Shoes實體。 例如:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Product>()
            .Map<Dress>(m => m.Requires("ProductCategoryID").HasValue(1))
            .Map<Shoes>(m => m.Requires("ProductCategoryID").HasValue(2));
}

在這種情況下,當您從DBContext加載它們時,它將自動創建所需的類型:

List<Product> products = dbContext.Products.ToList();
foreach(var product in products)
{
    var sale = product.GiveSale();
    if (product is Dress) Console.WriteLine("It's dress!");
    if (product is Shoes) Console.WriteLine("It's a pair of shoes!");       
}

然后您可以更新數據,並首先通過調用SaveChanges將Dress \\ Shoes作為常規Poco對象保存在Code中

EF將對象映射到表中,這是很明顯的方法,但是當進入多態時,DB並不是我們最好的朋友。

注意EF如何使您的實體成為部分類 這是為了您擴展它們。 因此,您可以編寫擴展類並將虛擬方法放在此處,然后繼續執行其他派生類。

假設這是生成的EF類:

public partial class Entity
{
    public int ID { get; set; }
    public string Name { get; set; }
    ...
}

然后,在另一個文件上, 在與 Entity 相同的名稱空間下編寫擴展類:

public partial class Entity
{
      public virtual int GiveSale()
      {
           return 0;
      }
}

繼續進行其余的層次結構:

public class Derived : Entity
{
     public override int GiveSale()
     {
           return your calculation;
     }
}

這樣,您仍然擁有實體框架類,並且可以自由擴展它,甚至可以使其成為層次結構的基類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM