使用Entity Framework 6创建计算属性 [英] Creating a computed property with Entity Framework 6
问题描述
我正在使用数据库优先方法,并且已经从数据库创建了模型.现在,我的Winforms应用程序中有一个datagrid视图,该视图已绑定到绑定源.一切正常(适当的数据显示在datagrid视图中).现在的问题是,如何添加一个包含两个值的计算属性(已在db中找到)?例如:
I am using Database First approach and I have created model from a database. Now I have a datagrid view in my Winforms app, that is bound to a binding source. And all that works fine (an appropriate data is shown in datagrid view). Now the problem is, how to add a computed property that consists of two values (already found in db) ? For an example:
让我们说我有一个表用户(id,用户名,first_name,last_name,user_type),但是我想在绑定的datagrid视图中有不同的列,并且我想拥有这些列:
Lets say that I have a table user (id, username, first_name, last_name, user_type) but I want to have different columns in my bound datagrid view, and I want to have these columns:
username, full name, type
其中"full name"
是我使用first_name + " " + last_name
会得到的.
where "full name"
is what would I get with first_name + " " + last_name
.
我想我不能像这样手动修改模型类:
I guess I can't just modify a model class manually like this:
public string FullName
{
get
{
return FirstName + " " + LastName;
}
protected set {}
}
因为此类是自动生成的,并且每次从现有数据库生成模型时(当我进行一些更改时),我的代码都会被删除,因此这不是真正的选择...
because this class is generated automatically , and my code will be deleted each time a generate models from an existing database (when I make some change), so this is not the real option...
推荐答案
实际上,我通过使用部分类功能解决了此问题: 我创建了另一个文件,该文件包含User模型类的另一部分(带有我的其他属性),一切正常.
Actually, I solved this by using partial class functionality: I have created another file that contains another portion of my User model class (with my additional properties) and everything went just fine.
namespace User.Model
{
public partial class User
{
public string FullName
{
get
{
return (this.firstName + " " + this.lastName;
}
protected set { }
}
}
}
现在,当我生成模型类时,此新文件不受EF的影响.另外,这个新字段也可以通过datagrid视图正确显示...
Now when I generate model classes, this new file is not affected by EF. Also this new field is correctly shown by datagrid view...
这篇关于使用Entity Framework 6创建计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!