使用实体框架,是否可以将方法添加到对象类? 例如,我有一个CLIENT映射,我想创建一个“getAgeFromBirhDate”方法。使用实体框架向模型添加方法
11
A
回答
20
是的。这是可能的。实体框架生成Partial Classes。
这意味着您可以创建另一个包含Partial Class定义的另一部分的文件(使用其他方法),并且一切都可以正常工作。
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
相关问题
- 1. 实体框架:跨方法使用模型的相同实例?
- 2. 使用实体框架数据模型添加验证属性
- 3. 实体框架添加到实体模型poco
- 4. 如何将视图添加到实体框架实体模型?
- 5. MVC 3实体模型 - 添加方法?
- 6. 无法将类对象添加到实体框架模型
- 7. 实体框架 - 使用视图模型
- 8. 跨层使用实体框架模型?
- 9. 实体框架模型使用远程
- 10. 不使用实体框架模型
- 11. 添加记录使用实体框架
- 12. 将实体框架添加到模块
- 13. 实体框架 - 从模型
- 14. ASP.Net实体框架模型
- 15. 使用实体框架实现MVVM模式 - 添加删除
- 16. 无法更新实体框架模型
- 17. 实体框架6:泛型方法AddOrUpdate
- 18. 实体框架在添加
- 19. 实体框架添加实体也添加子实体
- 20. 实体框架:ObjectSet.AddObject不添加实体?
- 21. 实体框架 - 添加子实体
- 22. 实体框架 - 当添加DbUpdateException实体
- 23. 实体框架添加新的实体
- 24. 实体框架核心查询特定模型两个方向
- 25. C# - 实体框架 - 加入方法
- 26. 实体框架:加入方法
- 27. 实体框架3.5不添加模型中的所有属性
- 28. 实体框架4 - 将现有模型添加到关联
- 29. 将属性添加到实体框架模型
- 30. 实体框架模型 - 不允许我添加某些表
; using System.Collections.Generic;使用System.Linq的 ; using System.Web; 命名空间FOO.Models { 公共部分类FOO_USERS { 公共无效栏(){ // 方法的代码在这里 }} } 这 – eka808 2010-11-30 16:37:40
代码工作:) – eka808 2010-11-30 16:38:04