简体   繁体   English

使用Entity Framework 6创建计算属性

[英]Creating a computed property with Entity Framework 6

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. 现在,我的Winforms应用程序中有一个datagrid视图,该视图已绑定到绑定源。 And all that works fine (an appropriate data is shown in datagrid view). 一切正常(适当的数据显示在datagrid视图中)。 Now the problem is, how to add a computed property that consists of two values (already found in db) ? 现在的问题是,如何添加一个包含两个值的计算属性(已在db中找到)? For an example: 例如:

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: 可以说我有一个表用户(id,username,first_name,last_name,user_type),但是我想在绑定的datagrid视图中有不同的列,并且我想拥有这些列:

username, full name, type

where "full name" is what would I get with first_name + " " + last_name . 使用first_name + " " + last_name可以获得"full 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... 因为此类是自动生成的,并且每次从现有数据库生成模型时(当我进行一些更改时),我的代码都会被删除,所以这不是真正的选择...

I still cant add comments, so I will have to do it this way. 我仍然无法添加评论,因此我将不得不采用这种方式。

Regarding your approach, why don't you create a data transfer model that you will bind to the data grid view? 关于您的方法,为什么不创建将绑定到数据网格视图的数据传输模型?

With this approach, your new model will have the needed property FullName and you can show this in your grid view. 使用这种方法,新模型将具有所需的属性FullName,并且可以在网格视图中显示它。 You database entity model will remain the same. 您的数据库实体模型将保持不变。 With this, you have decoupled the database model from the view model and achieved what you wanted. 这样,您就可以将数据库模型与视图模型分离,并实现所需的功能。

UPDATE: 更新:

/// <summary>
///     Assuming this is the EF model, generated with the database first approach. We leave it as is.
/// </summary>
public class UserEntityModel
{
    public int Id { get; set; }

    public string UserName { get; set; } 

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int UserType { get; set; }
}

/// <summary>
///     This model represents your grid presentation specific data. As you can see, we have the fields 
///     that we will show. This is the new DTO model
/// </summary>
public class UserGridViewModel
{
    public string UserName { get; set; }

    public string FullName { get; set; } 

    public int UserType { get; set; }
}

/// <summary>
///     This method demonstrates the retrieving and model to model mapping.
/// </summary> 
public UserGridViewModel GetUser(int userId)
{
      //retrieve the UserEntityModel
      var efObject = _context.User.Where(user => user.Id == userId).SingleOrDefault();

       if (efObject  == null) {
          return null;
       }

       // construct the new object, set the required data 
       return new UserGridViewModel()
       {
            UserName = efObject.UserName,
            UserType = efObject.UserType,
            FullName = $"{efObject.FirstName} {efObject.LastName}"
        };
}

Additional explanation: Let's assume that UserEntityModel is your database first generated data model. 附加说明:假设UserEntityModel是您的数据库首先生成的数据模型。 we will leave it as is. 我们将保持原样。

We will create a second model, UserGridViewModel that contains data only that you will show in your grid. 我们将创建第二个模型UserGridViewModel ,其中仅包含将在网格中显示的数据。 This is the DTO model. 这是DTO模型。

The GetUser Method should conceptually demonstrate the usage of the first (ef model) and then the second (DTO) model. GetUser方法应该在概念上演示第一个(ef模型)和第二个(DTO)模型的用法。 We retrieve the data from the database, we construct the DTO model and pass it to the grid. 我们从数据库中检索数据,构造DTO模型并将其传递给网格。

You can find more information here and here . 您可以在此处此处找到更多信息。

Hope this helps, cheers and happy coding! 希望这会有所帮助,欢呼和编码愉快!

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. 实际上,我通过使用部分类功能解决了这个问题:我创建了另一个文件,该文件包含User模型类的另一部分(带有我的其他属性),一切正常。

namespace User.Model
{
    public partial class User
    {
        public string FullName
        {
            get
            {
                return (this.firstName + " " + this.lastName;
            }
            protected set { }
        }
    }
}

Now when I generate model classes, this new file is not affected by EF. 现在,当我生成模型类时,此新文件将不受EF的影响。 Also this new field is correctly shown by datagrid view... 而且这个新字段也可以通过datagrid视图正确显示...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM