2010-11-30 33 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