使用entity framework向模型添加方法
使用entity framework,是否可以向对象类添加方法? 例如,我有一个CLIENT映射,我想创建一个“getAgeFromBirhDate”方法。
是。 这是可能的。 entity framework生成部分类 。
这意味着你可以创建另一个包含Partial Class定义的另一部分的文件(使用你的附加方法),一切都会正常工作。
第一个答案的一个例子:
如果你有一个名为Flower
的实体,你可以使用这个partial
类来为它添加方法:
namespace Garden //same as namespace of your entity object { public partial class Flower { public static Flower Get(int id) { // } } }
public static class ModelExtended { public static void SaveModelToXML(this Model1Container model, string xmlfilePath) { ///some code } }
假设您的部分类具有来自数据库的entity framework属性价格:
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 ; } } }
然后,无论您想在何处使用它,都可以创建自定义类对象,并在其中存储来自entity framework的对象:
//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