向实体框架添加自定义属性? [英] Adding A Custom Property To Entity Framework?
问题描述
显然,它的所有字段都在表中(ID,CategoryName,SortOrder等),但是我想知道是否可以添加不在表中的自定义属性,但实际上是自定义方法的结果
我想添加一个名为CategoryURL的新属性,它基本上是通过自定义方法运行的CategoryName属性,并返回一个连字符串。
我最初的想法是继承自生成的类别类,并在里面创建了一些类似的东西。
public string CategoryURL
{
get {return MyCustomMethod(this.CategoryName)}
}
这是正确的方法吗?并将'this.CategoryName'的工作,我认为应该?基本上,最终结果是当我返回一个类别列表时,我希望这是一个类的一部分,所以我可以在我的foreach循环中使用它。
希望这个有意义吗?
你应该使用 partial
class:
public partial class Category
{
public string CategoryURL
{
get {return MyCustomMethod(this.CategoryName); }
}
}
这样 CategoryName
将按照预期的方式工作。
这是因为实体框架代码生成器生成的类也会生成 partial
类。这也意味着您可以安全地从数据库重新生成类,而不会影响您自己定义的部分类。
I am using the Entity Framework for the first time and want to know if the following is possible - I have generated my classes from the DB, and have one called Category.
Obviously it has all my fields in the table (ID, CategoryName, SortOrder etc..) but I want to know if I can add a custom property which is not in the table, but is actually the result of a custom method.
I want to add a new property called 'CategoryURL' which is basically the 'CategoryName' property run through a custom method and returns a hyphenated string.
My initial thought is inheriting from the generated Category class and creating something like this inside?
public string CategoryURL
{
get{ return MyCustomMethod(this.CategoryName) }
}
Is this the correct approach? And will 'this.CategoryName' work as I think it should? Basically the end result is when I return a list of 'Category' I want this to be part of the class so I can use it in my foreach loop.
Hope this makes sense?
you should use a partial
class:
public partial class Category
{
public string CategoryURL
{
get{ return MyCustomMethod(this.CategoryName); }
}
}
This way this.CategoryName
will work just as expected.
This works because the classes generated by the entity framework code generator also generates partial
classes. It also means that you can safely re-generate the classes from the database without affecting the partial classes that you have defined yourself.
这篇关于向实体框架添加自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!