学习008-02-01-02 Implement a Data Model: Basics(实施数据模型:基础)

Implement a Data Model: Basics(实施数据模型:基础)

This lesson explains how to implement entity classes for your application and describes the basics of automatic user interface construction based on data.
本课介绍如何为您的应用程序实现实体类,并描述基于数据的自动用户交互界面构建的基础知识。

During this lesson, you will do the following:
在本课中,您将执行以下操作:

  • Add a simple entity class.(添加一个简单的实体类。)
  • Display the entity class in the application’s navigation control.(在应用程序的导航控件中显示实体类。)

Entity classes do not depend on the application UI. Implement them in a platform-independent module project. This way, other XAF or non-XAF applications can share entities.
实体类不依赖于应用程序UI。在platform-independent模块项目中实现它们。这样,其他XAF或非XAF应用程序可以共享实体。

Inherit your entity classes from the base persistent class DevExpress.Persistent.BaseImpl.EF.BaseObject. The BaseObject class implements the IXafEntityObject and IObjectSpaceLink interfaces. This means that CRUD operations for the declared objects are available automatically and you don’t need to implement them in your code.
从基本持久类DevExpress. Persis.BaseImpl.EF.BaseObject继承您的实体类。BaseObject类实现IXafEntityObject和IObjectSpaceLink接口。这意味着声明对象的CRUD操作是自动可用的,您不需要在代码中实现它们。

For additional information on these concepts, refer to the following topic: Views.
有关这些概念的更多信息,请参阅以下主题:视图。

Step-by-Step Instructions(分步说明)

1.Expand the MySolution.Module project and right-click the Business Objects folder. Choose Add | Class…. Specify Employee.cs as the new class name and click Add. Replace the auto-generated code with the following class declaration:
展开MySolutions. Module项目并右键单击Business Objects文件夹。选择添加|类……将员工.cs指定为新类名,然后单击添加。将自动生成的代码替换为以下类声明:

C#

using DevExpress.Persistent.BaseImpl.EF;

namespace MySolution.Module.BusinessObjects;

public class Employee : BaseObject {

    public virtual String FirstName { get; set; }

    public virtual String LastName { get; set; }

    public virtual String MiddleName { get; set; }

}

2.Go to the MySolution.Module\BusinessObjects\MySolutionDbContext file and add the following property to the MySolutionEFCoreDbContext entity container class:
转到MySolutions. Module\BusinessObjects\MySolutionDbContext文件并将以下属性添加到MySolutionEFCoreDbContext实体容器类:

C#

Module.BusinessObjects {
    public class MySolutionEFCoreDbContext : DbContext {
        //...
        public DbSet<Employee> Employees { get; set; }
    }
}

This property is a collection of Employee class objects. XAF creates a table with the same name in the database and then maps this collection to the table.
此属性是员工类对象的集合。XAF在数据库中创建一个同名表,然后将此集合映射到表。

Tip
If you inherit an entity class from another entity class, you can register both entities in the DbContext class. This way, your application can work with collections of ancestor class objects.
如果您从另一个实体类继承一个实体类,您可以在DbContext类中注册这两个实体。这样,您的应用程序可以使用祖先类对象的集合。

Propagate Data Model Structure Changes to the Database(将数据模型结构更改传播到数据库)

Your application now contains data objects. This means that the application requires a database. You have the following options to choose from:
您的应用程序现在包含数据对象。这意味着应用程序需要一个数据库。您有以下选项可供选择:

  • Use a DBMS to maintain the database.(使用DBMS来维护数据库。)
    This option requires you to set up database migrations.
    此选项要求您设置数据库迁移。

  • *Use an in-memory database.(*使用内存数据库。)
    This option works best during the development/debugging stage. You only need to update the data connection code.
    此选项在开发/调试阶段效果最好。您只需要更新数据连接代码。

If you cannot work with an in-memory database, you can drop the database after you change the business model. Note that this action clears all previously added data records. If you need to keep the data between application runs, update the database whenever you make changes to the data model (create a new class, add a new attribute to an existing class, rename a class or an attribute, and so on).
如果您无法使用内存中的数据库,则可以在更改业务模型后删除数据库。请注意,此操作会清除所有以前添加的数据记录。如果您需要在应用程序运行之间保留数据,请在更改数据模型时更新数据库(创建新类、向现有类添加新属性、重命名类或属性,等等)。

Use a DBMS: Setup Migrations(使用DBMS:设置迁移)

Since this tutorial uses Entity Framework Core, changes to the application’s data model may cause database-related exceptions when you run the application. The exception occurs if the database structure does not correspond to the structure of the business model classes.
由于本教程使用Entity Framework Core,因此在运行应用程序时,对应用程序数据模型的更改可能会导致与数据库相关的异常。如果数据库结构与业务模型类的结构不对应,则会发生异常。

In this tutorial, we use migrations to update the database schema because this feature is native to EF Core and is quick to implement. Before you run the application for the first time, or anytime after you change the Data Model, you need to create a migration and update the database. To do this, follow the steps below.
在本教程中,我们使用迁移来更新数据库模式,因为此功能是EF Core的原生功能,并且可以快速实现。在首次运行应用程序之前,或更改数据模型后的任何时候,您都需要创建迁移并更新数据库。为此,请按照以下步骤操作。

Important
Delete an existing database if there is one before you proceed, because Entity Framework Core does not take the existing database schema into consideration when it generates the first migration.
在继续之前删除现有数据库(如果有),因为Entity Framework Core在生成第一次迁移时不会考虑现有数据库模式。

1.Add the Microsoft.EntityFrameworkCore.Tools NuGet package to the MySolution.Module project. Build the solution.
将Microsoft.EntityFrameworkCore.ToolsNuGet包添加到MySolutions. Module项目。

Note
The package’s version must correspond to the version of EF Core supported in XAF.
包的版本必须与XAF支持的EF Core版本相对应。
Currently, we support Entity Framework Core 8.x.x. To find out which precise version you have, check the Microsoft.EntityFrameworkCore package in the dependencies of the YourProjectName.Module project.
目前,我们支持Entity Framework Core 8. x.x。要了解您拥有的精确版本,请查看YourProjectName.Module项目依赖项中的Microsoft.EntityFrameworkCore包。

2.In the MySolution.Module project, go to the BusinessObjects folder and open the MySolutionDbContext.cs file. Replace the declaration of the MySolutionDesignTimeDbContextFactory class with the code below:
在MySolutions. Module项目中,转到BusinessObjects文件夹并打开MySolutionDbContext.cs文件。将MySolutionDesignTimeDbContextFactory类的声明替换为以下代码:

C#

namespace MySolution.Module.BusinessObjects;
//...public class MySolutionDesignTimeDbContextFactory : IDesignTimeDbContextFactory<MySolutionEFCoreDbContext> {
   public MySolutionEFCoreDbContext CreateDbContext(string[] args) {
      // Throw new InvalidOperationException ("Make sure that the database connection string and connection provider are correct. After that, uncomment the code below and remove this exception.")
      var optionsBuilder = new DbContextOptionsBuilder<MySolutionEFCoreDbContext>();
      optionsBuilder.UseSqlServer("Integrated Security=SSPI;Pooling=false;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MySolution");
      //Automatically implements the INotifyPropertyChanged interface in the business objects
      optionsBuilder.UseChangeTrackingProxies();
      optionsBuilder.UseObjectSpaceLinkProxies();
      return new MySolutionEFCoreDbContext(optionsBuilder.Options);
   }
}

In the above code sample, the optionsBuilder.UseChangeTrackingProxies method enables the change-tracking proxies extension so that the application’s UI correctly reflects changes in data model. Refer to the Change Tracking in EF Core DbContext and Performance Considerations article for more information on change tracking in XAF applications with Entity Framework Core data models.
在上述代码示例中,optionsBuilder.UseChangeTrackingProxies 方法启用了变更跟踪代理扩展,以便应用程序的用户界面正确反映数据模型中的更改。有关使用实体框架核心数据模型的 XAF 应用程序中的变更跟踪的更多信息,请参考“EF Core DbContext 中的变更跟踪和性能注意事项”一文。

3.In Visual Studio, open the Package Manager Console and use the following command to add a migration:
在Visual Studio中,打开包管理器控制台并使用以下命令添加迁移:

cli
add-migration MyInitialMigrationName -StartupProject “MySolution.Module” -Project “MySolution.Module”

4.Update the database with the following command:
使用以下命令更新数据库:

cli
update-database -StartupProject “MySolution.Module” -Project “MySolution.Module”

You must update the database whenever you change the data model of your application, for example, when you add, rename, or delete a class or property. To do this, repeat steps 3 and 4 of this tutorial. Make sure to use a unique migration name for each new migration.
每当您更改应用程序的数据模型时,您都必须更新数据库,例如,当您添加、重命名或删除类或属性时。为此,请重复本教程的步骤3和4。确保为每个新迁移使用唯一的迁移名称。

Use an In-memory Database(使用内存数据库)

Open the MySolution.Blazor.Server\Startup.cs file, comment the UseSqlServer option, and uncomment the UseInMemoryDatabase option as displayed in the code snippet below. Do the same in the MySolution.Win\Startup.cs file.
打开MySolutions. Blazor.Server\Startup.cs文件,注释UseSqlServer选项,并取消注释UseInMemoryDatabase选项,如下面的代码片段所示。在MySolution.Win\Startup.cs文件中执行相同操作。

ASP.NET Core Blazor

//..namespace MySolution.Blazor.Server;


public class Startup {
    public Startup(IConfiguration configuration) {
        Configuration = configuration;
    }


    public IConfiguration Configuration { get; }


    // ...
    public void ConfigureServices(IServiceCollection services) {
        services.AddSingleton(typeof(Microsoft.AspNetCore.SignalR.HubConnectionHandler<>), typeof(ProxyHubConnectionHandler<>));
        //...
        services.AddXaf(Configuration, builder => {
            //...
            builder.ObjectSpaceProviders
                .AddEFCore().WithDbContext<MySolution.Module.BusinessObjects.MySolutionEFCoreDbContext>((serviceProvider, options) => {
                    // ...
                    options.UseInMemoryDatabase("InMemory");
                    string connectionString = null;
                    if(Configuration.GetConnectionString("ConnectionString") != null) {
                        connectionString = Configuration.GetConnectionString("ConnectionString");
                    }
                    //...
                    ArgumentNullException.ThrowIfNull(connectionString);
                    //options.UseSqlServer(connectionString);
                    options.UseChangeTrackingProxies();
                    options.UseObjectSpaceLinkProxies();
                    options.UseLazyLoadingProxies();
                })
                // ...
         });
    }
}

Windows Form

// ...namespace MySolution.Win;


public class ApplicationBuilder : IDesignTimeApplicationFactory {
    public static WinApplication BuildApplication(string connectionString) {
        // ...
        builder.ObjectSpaceProviders
            .AddEFCore().WithDbContext<MySolution.Module.BusinessObjects.MySolutionEFCoreDbContext>((application, options) => {
                // ...
                options.UseInMemoryDatabase("InMemory");
                //options.UseSqlServer(connectionString);
                options.UseChangeTrackingProxies();
                options.UseObjectSpaceLinkProxies();
            })


        // ...
    }


    // ...
}

Application Run(应用程序运行)

1.Run the application. You can see that the UI did not change. To make the Employee item visible in the application’s navigation control, add the DefaultClassOptionsAttribute attribute to the class:
运行应用程序。您可以看到UI没有改变。要使员工项目在应用程序的导航控件中可见,请将DefaultClassOptionsAttribute属性添加到类中:

C#

//...

namespace MySolution.Module.BusinessObjects;

[DefaultClassOptions]
public class Employee : BaseObject
{

    //...
}

//...

With this attribute, you can also use Employee objects as data sources to generate reports. For additional information, refer to the following lesson of this tutorial: Create and Preview a Report.
使用此属性,您还可以使用员工对象作为数据源来生成报告。有关其他信息,请参阅本教程的以下课程:创建和预览报告。

To apply each option separately, use the NavigationItemAttribute and VisibleInReportsAttribute attributes.
要分别应用每个选项,请使用NavigationItemAttribute和VisibleInReportsAttribute属性。

2.Add another migration and update the database.
添加另一个迁移并更新数据库。

3.Run the application. XAF generates a user interface that is based on the specified data structures. The List View displays the collection of objects of the Employee class. Since there are no objects of this type, the Employee List View is empty for now:
运行应用程序。XAF生成一个基于指定数据结构的用户交互界面。列表视图显示员工类的对象集合。由于没有这种类型的对象,员工列表视图暂时为空:

ASP.NET Core Blazor
在这里插入图片描述

Windows Forms
在这里插入图片描述

4.Click the New button to invoke the Detail View for a new object of the Employee type. XAF renders the properties of the entity class as data fields. The Detail View contains editors for each data field.
单击新建按钮为员工类型的新对象调用详细信息视图。XAF将实体类的属性呈现为数据字段。详细信息视图包含每个数据栏的编辑器。

ASP.NET Core Blazor
在这里插入图片描述

Windows Forms
在这里插入图片描述

Next Lesson(下一课)

Extend the Data Model
扩展数据模型

  • 32
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤姆•猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值