向实体框架添加自定义属性? [英] Adding A Custom Property To Entity Framework?

查看:102
本文介绍了向实体框架添加自定义属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用实体框架,想知道是否有可能 - 我已经从DB生成了我的类,并且有一个叫做Category。



显然,它的所有字段都在表中(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆