阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

.NET Core1.1+VS2017RC+MySQL+EF搭建多层Web应用程序

146次阅读
没有评论

共计 3881 个字符,预计需要花费 10 分钟才能阅读完成。

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序,先贴上解决方案截图

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序

一、新建 4 个解决方案文件夹

1-Presentation

2-Application

3-Domain

4-Infrastructure

二、在解决方案文件夹中分别创建项目

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序

新建.NET Core Web 应用程序,【身份验证】需要选择【个人用户账户】否则无法执行 migrations 操作,猜想原因可能少了某个 NuGet 包,具体没去测试验证

如果不选【个人用户账户】,migrations 操作时会报【No executable found matching command “dotnet-ef”】错误

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序

其余项目创建省略

项目引用关系:

1.ContosoUniversity.WebAdmin 引用 ContosoUniversity.Application、ContosoUniversity.Domain

2.ContosoUniversity.Application 引用 ContosoUniversity.Repository、ContosoUniversity.Domain

3.ContosoUniversity.Repository 引用 ContosoUniversity.Domain

4.ContosoUniversity.Domain 不引用任何项目

三、ContosoUniversity.Domain 项目中添加Microsoft.EntityFrameworkCore.Tools 1.1.0-preview4-final

NuGet 命令:Install-Package Microsoft.EntityFrameworkCore.Tools -Pre

四、ContosoUniversity.Domain 项目添加 Student、SchoolContext、DbInitializer 类

Student:POCO 对象,对应数据库中的 Student 表

SchoolContext:数据库上下文,用于数据库 CRUD 以及 Migrations 操作

DbInitializer:初始化数据库并添加测试数据

using System;

namespace ContosoUniversity.Domain
{public class Student
    {public int ID {get; set; }
        public string LastName {get; set; }
        public string FirstMidName {get; set; }
        public DateTime EnrollmentDate {get; set; }
    }
}
 
 
using Microsoft.EntityFrameworkCore;

namespace ContosoUniversity.Domain.Data
{public class SchoolContext : DbContext
    {public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
        { }

        public DbSet<Student> Students {get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {modelBuilder.Entity<Student>().ToTable("Student");
        }
    }
}
 
 
using System;
using System.Linq;

namespace ContosoUniversity.Domain.Data
{public static class DbInitializer
    {public static void Initialize(SchoolContext context)
        {context.Database.EnsureCreated();

            // Look for any students.
            if (context.Students.Any())
            {return;   // DB has been seeded
            }

            var students = new Student[]
            {new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
            new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
            new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
            };
            foreach (Student s in students)
            {context.Students.Add(s);
            }
            context.SaveChanges();}
    }
}

五、ContosoUniversity.WebAdmin 项目修改

1.appsetting.json 文件添加 MySQL 连接字符串

"ConnectionStrings": {"DefaultConnection": "server=xxx;user id=xxx;password=xxx;database=ContosoUniversity;"
  }

2. 添加 NuGet 包 MySql.Data 6.10.0-alpha、MySql.Data.EntityFrameworkCore 6.10.0-alpha、Microsoft.EntityFrameworkCore.Tools 1.1.0-preview4-final

MySql 版本不要选 7.0.6-IR31,项目跑起来会报 ”MySql.Data.EntityFrameworkCore.Storage.Internal.MySQLCommandBuilderFactory..ctor(ISensitiveDataLogger<RelationalCommandBuilderFactory> logger, DiagnosticSource diagnosticSource, IRelationalTypeMapper typeMapper)” 错误

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序

 

3.StartUp 类 ConfigureServices 方法注入数据库上下文

public void ConfigureServices(IServiceCollection services)
        {services.AddDbContext<SchoolContext>(options =>
                options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("ContosoUniversity.WebAdmin")));

            // Add framework services.
            services.AddMvc();}

注意,标红的代码不可缺少,否则 EntityFramework 无法执行 Migrations,报错信息如下

.NET Core1.1+VS2017RC+MySQL+EF 搭建多层 Web 应用程序

 

4.StartUp 添加数据库初始化

改造 Configure 方法签名,添加 SchoolContext 参数

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context)

Configure 方法末尾添加数据库初始化代码

DbInitializer.Initialize(context);

 最后

把其余各层的代码都加上项目就可以跑起来了,通过 Migrations 操作维护开发库,.NET Core+MySQL+EF 使用 VS2017RC 构建项目的坑基本就是这些了。。

注意

NuGet 包 Install 或 Uninstall 命名执行后,查看 VS2017RC 中依赖的 NuGet 包发现没有变化(实际上已 InstallUninstall,VS2017RC 没有刷新),此时需要关闭解决方案重新打开,这时 NuGet 依赖才会刷新,这时 VS2017RC 的一个 BUG!

 

s

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-21发表,共计3881字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中