带有ASP.NET Core的dhtmlxGantt教程:如何创建一个项目(二)

本教程为您提供有关如何在服务器端使用ASP.NET Core 2 创建Gantt的分步说明。

dhtmlxGantt是用于跨浏览器和跨平台应用程序的功能齐全的Gantt图表。可满足项目管理应用程序的所有需求,是最完善的甘特图图表库。它允许你创建动态甘特图,并以一个方便的图形化方式可视化项目进度。有了dhtmlxGantt,你可以显示活动之间的依赖关系,显示具有完成百分比阴影的当前任务状态以及组织活动到树结构。

dhtmlxGantt试用版

步骤3.创建模型和数据库

让我们从数据模型开始。Gantt的数据模型包括链接和任务。从.NET世界的角度来看,dhtmlxGantt 对模型属性使用非常规名称。有时,客户端模型还包含一些用于客户端或后端逻辑的属性,但是这些属性不应存储在数据库中。

为了解决这个问题,将使用数据传输对象(DTO)模式。将定义两种模型:

  • 将与EF Core一起使用且在应用程序内部的域模型类
  • 用于与Web API通信的DTO类。

然后应在两个模型之间实现映射。

在项目文件夹中创建一个名为Models的新文件夹。在此处将实现模型类和EF上下文。

任务模型

首先,为“任务”创建一个类。在文件夹中的模型创建一个文件并将其命名为Task.cs。可以通过调用Models文件夹的上下文菜单并选择Add-> Class来完成。
该模型必须如下所示:

DHX.Gantt /Models/Task.csusing System;namespace DHX.Gantt.Models{    public class Task    {        public int Id { get; set; }        public string Text { get; set; }        public DateTime StartDate { get; set; }        public int Duration { get; set; }        public decimal Progress { get; set; }        public intParentId { get; set; }        public string Type { get; set; }    }}

您可以查找Task对象的所有属性的列表。

链接模型

再添加一个文件并为Links创建一个类:

DHX.Gantt /Models/Link.csnamespace DHX.Gantt.Models{    public class Link    {        public int Id { get; set; }        public string Type { get; set; }        public int SourceTaskId { get; set; }        public int TargetTaskId { get; set; }    }}

模型已准备就绪,您可以开始配置数据库连接。

配置数据库连接

要配置数据库连接,您需要采取以下步骤:

安装实体框架核心

在实体框架的核心将被用来管理与数据库应用程序的通信。让我们安装框架:

  • 在项目树中找到DHTMLX.Gantt的依赖项
  • 调用上下文菜单,然后选择“ 管理NuGet包”
  • 打开浏览选项卡并安装Microsoft.EntityFrameworkCore.SqlServer

带有ASP.NET Core的dhtmlxGantt教程:如何创建一个项目(二)

创建实体上下文

接下来,您需要定义与数据库的会话并启用加载和保存数据。为此,创建上下文:

  • 在模型文件夹中添加GanttContext.cs文件
  • 在创建的文件中定义GanttContext类

DHX.Gantt /ModelsGanttContext.csusing Microsoft.EntityFrameworkCore;namespace DHX.Gantt.Models{    public class GanttContext : DbContext    {        public GanttContext(DbContextOptions<GanttContext> options)           : base(options)        {        }        public DbSet<Task> Tasks { get; set; }        public DbSet<Link> Links { get; set; }    }}

将第一条记录添加到数据库

现在您可以将记录添加到数据库。让我们创建一个数据库初始化程序,用任务填充数据库。在“ 模型”文件夹中定义一个类,并将其命名为GanttSeeder。该类将具有Seed()方法,该方法将向数据库添加任务和链接。

DHX.Gantt /Models/GanttSeeder.csusing System;using System.Collections.Generic;using System.Linq;using Microsoft.EntityFrameworkCore;namespace DHX.Gantt.Models{    public static class GanttSeeder    {        public static void Seed(GanttContext context)        {            if (context.Tasks.Any())            {                return;   // DB has been seeded            }            using (var transaction = context.Database.BeginTransaction())            {               List<Task> tasks = new List<Task>()               {                  new Task()                    {                       Id = 1,                       Text = "Project #2",                       StartDate = DateTime.Today.AddDays(-3),                       Duration = 18,                       Progress = 0.4m,                       ParentId = null                    },                    new Task()                    {                       Id = 2,                       Text = "Task #1",                       StartDate = DateTime.Today.AddDays(-2),                       Duration = 8,                       Progress = 0.6m,                       ParentId = 1                    },                    new Task()                    {                       Id = 3,                       Text = "Task #2",                       StartDate = DateTime.Today.AddDays(-1),                       Duration = 8,                       Progress = 0.6m,                       ParentId = 1                    }               };               tasks.ForEach(s => context.Tasks.Add(s));               context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Tasks ON;");               context.SaveChanges();               context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Tasks OFF;");               List<Link> links = new List<Link>()               {                   new Link() {Id = 1, SourceTaskId = 1, TargetTaskId = 2, Type = "1"},                   new Link() {Id = 2, SourceTaskId = 2, TargetTaskId = 3, Type = "0"}               };               links.ForEach(s => context.Links.Add(s));               context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Links ON;");               context.SaveChanges();               context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Links OFF;");               transaction.Commit();            }        }    }}

注册数据库

现在,您应该在Startup.cs中注册数据库。但是首先,您需要一个连接字符串。它将存储
在应用程序设置中的JSON文件中。创建appsettings.json文件(如果已有,请打开它)并将连接字符串添加到数据库:

appsettings.json{  "ConnectionStrings": {    "DefaultConnection": "Server=(localdb)\mssqllocaldb;        Database=GanttDatabase;Trusted_Connection=True;"  }}

数据库上下文将通过依赖项注入进行注册 。
将以下名称空间添加到Startup.cs:
启动文件

using Microsoft.EntityFrameworkCore;using DHX.Gantt.Models;using Microsoft.Extensions.Configuration;

该声明将如下所示:
启动文件

public IConfiguration Configuration { get; }public Startup(IConfiguration configuration){    Configuration = configuration;}public void ConfigureServices(IServiceCollection services){    services.AddDbContext<GanttContext>(options =>        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));}

这是Startup.cs的完整代码:

启动文件

using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.DependencyInjection;using Microsoft.EntityFrameworkCore;using DHX.Gantt.Models;using Microsoft.Extensions.Configuration;namespace DHX.Gantt{ public class Startup   {    public IConfiguration Configuration { get; }    public Startup(IConfiguration configuration)     {        Configuration = configuration;     }     //This method is called by the runtime. Use it to add services to the container.     //More info on app config here - https://go.microsoft.com/fwlink/inkID=398940     public void ConfigureServices(IServiceCollection services)     {       services.AddDbContext<GanttContext>(options =>         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));     }     //The method is called by the runtime. Use it to configure HTTP request pipeline.     public void Configure(IApplicationBuilder app, IHostingEnvironment env)     {       if (env.IsDevelopment())       {          app.UseDeveloperExceptionPage();       }       app.UseDefaultFiles();       app.UseStaticFiles();     }  }}

最后,您需要在应用程序启动时初始化数据库并为其添加种子。通常,您希望为此使用迁移,但为简单起见,此处未使用它们。

让我们从创建一个将要完成初始化的类开始。在“ 模型”文件夹中创建GanttInitializerExtension.cs文件:

Models/GanttInitializerExtension.csusing Microsoft.Extensions.DependencyInjection;using Microsoft.AspNetCore.Hosting;namespace DHX.Gantt.Models{  public static class GanttInitializerExtension  {    public static IWebHost InitializeDatabase(this IWebHost webHost)    {      var serviceScopeFactory =       (IServiceScopeFactory)webHost.Services.GetService(typeof(IServiceScopeFactory));      using (var scope = serviceScopeFactory.CreateScope())       {          var services = scope.ServiceProvider;          var dbContext = services.GetRequiredService<GanttContext>();          dbContext.Database.EnsureCreated();          GanttSeeder.Seed(dbContext);       }       return webHost;     }   }}

接下来在Program.Main管道中调用InitializeDatabase():

Program.csusing Microsoft.AspNetCore;using Microsoft.AspNetCore.Hosting;using DHX.Gantt.Models;namespace DHX.Gantt{    public class Program    {        public static void Main(string[] args)        {            BuildWebHost(args)                .InitializeDatabase()                .Run();        }        public static IWebHost BuildWebHost(string[] args) =>            WebHost.CreateDefaultBuilder(args)                .UseStartup<Startup>()                .Build();    }}

如上所述,本教程中未使用迁移。取而代之的是使用简单的ConfirmCreated和seed。

当前部分已经完成,让我们回到甘特。

定义DTO和映射

现在是时候定义将用于Web API的DTO类了。让我们从Task的DTO类开始。在“ 模型”文件夹中,创建一个文件并定义WebApiTask.cs类:

Models/WebApiTask.csusing System;namespace DHX.Gantt.Models{    public class WebApiTask    {        public int id { get; set; }        public string text { get; set; }        public string start_date { get; set; }        public int duration { get; set; }        public decimal progress { get; set; }        public intparent { get; set; }        public string type { get; set; }        public bool open        {            get { return true; }            set { }        }        public static explicit operator WebApiTask(Task task)        {            return new WebApiTask            {                id = task.Id,                text = task.Text,                start_date = task.StartDate.ToString("yyyy-MM-dd HH:mm"),                duration = task.Duration,                parent = task.ParentId,                type = task.Type,                progress = task.Progress            };        }        public static explicit operator Task(WebApiTask task)        {            return new Task            {                Id = task.id,                Text = task.text,                StartDate = DateTime.Parse(task.start_date,                    System.Globalization.CultureInfo.InvariantCulture),                Duration = task.duration,                ParentId = task.parent,                Type = task.type,                Progress = task.progress            };        }    }}

这是在Models文件夹中名为WebApiLink.cs的文件中定义的Link的DTO类:

Models/WebApiLink.csnamespace DHX.Gantt.Models{    public class WebApiLink    {        public int id { get; set; }        public string type { get; set; }        public int source { get; set; }        public int target { get; set; }        public static explicit operator WebApiLink(Link link)        {            return new WebApiLink            {                id = link.Id,                type = link.Type,                source = link.SourceTaskId,                target = link.TargetTaskId            };        }        public static explicit operator Link(WebApiLink link)        {            return new Link            {                Id = link.id,                Type = link.type,                SourceTaskId = link.source,                TargetTaskId = link.target            };        }    }}

完成此步骤后,应获得以下文件夹结构:

带有ASP.NET Core的dhtmlxGantt教程:如何创建一个项目(二) 现在,您可以运行该应用程序以检查一切是否就绪。如果您没有看到运行时错误,那么一切都很好。

是否想尝试DHTMLX Gantt来构建自己的Salesforce应用问我们的GitHub存储库,您可以在其中找到Salesforce的Gantt组件的完整源代码,并按照我们的视频指南中的步骤进行操作。

关产品推荐:

VARCHART XGantt:支持ActiveX、.Net等平台的C#甘特图控件

AnyGantt:构建复杂且内容丰富的甘特图的理想工具

jQuery Gantt Package:基于HTML5 / jQuery的跨平台jQuery Gantt包

phGantt Time Package:对任务和时间的分配管理的甘特图

APS帮助提升企业生产效率,真正实现生产计划可视化呈现与控制,快速有效响应不同场景的生产计划,提高准时交货能力,提高产能和资源利用率

想要购买dhtmlxGantt正版授权,或了解更多产品信息请点击【咨询在线客服】 带有ASP.NET Core的dhtmlxGantt教程:如何创建一个项目(二)
标签:

来源:慧都

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2020年7月13日
下一篇 2020年7月13日

相关推荐

发表回复

登录后才能评论