2010-11-30 34 views

回答

20

是的。這是可能的。實體框架生成Partial Classes

這意味着您可以創建另一個包含Partial Class定義的另一部分的文件(使用其他方法),並且一切都可以正常工作。

+0

; using System.Collections.Generic;使用System.Linq的 ; using System.Web; 命名空間FOO.Models { 公共部分類FOO_USERS { 公共無效欄(){ // 方法的代碼在這裏 }} } 這 – eka808 2010-11-30 16:37:40

+0

代碼工作:) – eka808 2010-11-30 16:38:04

2
public static class ModelExtended 
{ 
    public static void SaveModelToXML(this Model1Container model, string xmlfilePath) 
    { 
     ///some code 
    } 
} 
4

的第一個答案的一個例子:

,如果你有一個名爲Flower實體您可以使用此partial類添加方法給它:

namespace Garden //same as namespace of your entity object 
{ 
    public partial class Flower 
    { 
     public static Flower Get(int id) 
     { 
      // 
     } 
    } 
} 
0

假設你有你的部分類一個實體框架屬性價格從數據庫:

namespace Garden //same as namespace of your entity object 
    { 
     public partial class Flower 
     { 
      public int price; 
      public string name; 
      // Any other code ... 
     } 
    } 

如果您不想使用另一個分部類,則可以定義包含作爲屬性存儲的原始實體的自定義類。您可以添加那麼任何額外的自定義屬性和方法

namespace Garden //same as namespace of your entity object 
{ 
    public class CustomFlower 
    { 
     public Flower originalFlowerEntityFramework; 

     // An extra custom attribute 
     public int standardPrice; 


     public CustomFlower(Flower paramOriginalFlowerEntityFramework) 
     { 
      this.originalFlowerEntityFramework = paramOriginalFlowerEntityFramework 
     } 


     // An extra custom method 
     public int priceCustomFlowerMethod() 
     { 
      if (this.originalFlowerEntityFramework.name == "Rose") 
       return this.originalFlowerEntityFramework.price * 3 ; 
      else 
       return this.price ; 
     } 

    } 
} 

那麼無論你想使用它,您可以創建自定義類的對象,並存儲在其從實體框架的一個:使用系統

//Your Entity Framework class 
Flower aFlower = new Flower(); 
aFlower.price = 10; 
aFlower.name = "Rose"; 

// or any other code ... 

// Your custom class 
CustomFlower cFlower = new CustomFlower(aFlower); 
cFlower.standardPrice = 20; 

MessageBox.Show("Original Price : " + cFlower.originalFlowerEntityFramework.price); 
// Will display 10 
MessageBox.Show("Standard price : " + cFlower.standardPrice); 
// Will display 20 
MessageBox.Show("Custom Price : " + cFlower.priceCustomFlowerMethod()); 
// Will display 30