ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

Stella981
• 阅读 737

2019-08-23 11:07:09

1. 项目创建

1.1 安装

  下载.NETCORE SDK 进行安装

  下载NETCORE RUNTIME进行安装.

  下载Runtime & Hosting Bundle进行安装

  下载地址:https://dotnet.microsoft.com/download/dotnet-core

  微软的安装在windows方面很简单,基本就是一键安装.

1.2 开发工具

            VisualStudio 2019

1.3建立项目工程

  点击文件创建项目,出现如下图示

ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

  选择画红圈部分,接着出现如下图示

ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

1.4 新建Models文件夹,创建数据库实体类

 ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

1.5 创建数据库上下文类

  创建继承DbContext的上下文类,将数据库实体添加到DbSet中,重写OnModelCreating方

 1 public class SchoolContext : DbContext
 2     {
 3         public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
 4         {
 5         }
 6 
 7         public DbSet<Course> Courses { get; set; }
 8         public DbSet<Enrollment> Enrollments { get; set; }
 9         public DbSet<Student> Students { get; set; }
10         public DbSet<Department> Departments { get; set; }
11         public DbSet<Instructor> Instructors { get; set; }
12         public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
13         public DbSet<CourseAssignment> CourseAssignments { get; set; }
14 
15         protected override void OnModelCreating(ModelBuilder modelBuilder)
16         {
17             modelBuilder.Entity<Course>().ToTable("Course");
18             modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
19             modelBuilder.Entity<Student>().ToTable("Student");
20             modelBuilder.Entity<Department>().ToTable("Department");
21             modelBuilder.Entity<Instructor>().ToTable("Instructor");
22             modelBuilder.Entity<OfficeAssignment>().ToTable("OfficeAssignment");
23             modelBuilder.Entity<CourseAssignment>().ToTable("CourseAssignment");
24 
25             modelBuilder.Entity<CourseAssignment>()
26                 .HasKey(c => new { c.CourseID, c.InstructorID });
27         }
28     }

1.6使用测试数据设定数据库种子

  1 using System;
  2 using System.Linq;
  3 using Microsoft.EntityFrameworkCore;
  4 using Microsoft.Extensions.DependencyInjection;
  5 using ContosoUniversity.Models;
  6 
  7 namespace ContosoUniversity.Data
  8 {
  9     public static class DbInitializer
 10     {
 11         public static void Initialize(SchoolContext context)
 12         {
 13             //context.Database.EnsureCreated();
 14 
 15             // Look for any students.
 16             if (context.Students.Any())
 17             {
 18                 return;   // DB has been seeded
 19             }
 20 
 21             var students = new Student[]
 22             {
 23                 new Student { FirstMidName = "Carson",   LastName = "Alexander",
 24                     EnrollmentDate = DateTime.Parse("2010-09-01") },
 25                 new Student { FirstMidName = "Meredith", LastName = "Alonso",
 26                     EnrollmentDate = DateTime.Parse("2012-09-01") },
 27                 new Student { FirstMidName = "Arturo",   LastName = "Anand",
 28                     EnrollmentDate = DateTime.Parse("2013-09-01") },
 29                 new Student { FirstMidName = "Gytis",    LastName = "Barzdukas",
 30                     EnrollmentDate = DateTime.Parse("2012-09-01") },
 31                 new Student { FirstMidName = "Yan",      LastName = "Li",
 32                     EnrollmentDate = DateTime.Parse("2012-09-01") },
 33                 new Student { FirstMidName = "Peggy",    LastName = "Justice",
 34                     EnrollmentDate = DateTime.Parse("2011-09-01") },
 35                 new Student { FirstMidName = "Laura",    LastName = "Norman",
 36                     EnrollmentDate = DateTime.Parse("2013-09-01") },
 37                 new Student { FirstMidName = "Nino",     LastName = "Olivetto",
 38                     EnrollmentDate = DateTime.Parse("2005-09-01") }
 39             };
 40 
 41             foreach (Student s in students)
 42             {
 43                 context.Students.Add(s);
 44             }
 45             context.SaveChanges();
 46 
 47             var instructors = new Instructor[]
 48             {
 49                 new Instructor { FirstMidName = "Kim",     LastName = "Abercrombie",
 50                     HireDate = DateTime.Parse("1995-03-11") },
 51                 new Instructor { FirstMidName = "Fadi",    LastName = "Fakhouri",
 52                     HireDate = DateTime.Parse("2002-07-06") },
 53                 new Instructor { FirstMidName = "Roger",   LastName = "Harui",
 54                     HireDate = DateTime.Parse("1998-07-01") },
 55                 new Instructor { FirstMidName = "Candace", LastName = "Kapoor",
 56                     HireDate = DateTime.Parse("2001-01-15") },
 57                 new Instructor { FirstMidName = "Roger",   LastName = "Zheng",
 58                     HireDate = DateTime.Parse("2004-02-12") }
 59             };
 60 
 61             foreach (Instructor i in instructors)
 62             {
 63                 context.Instructors.Add(i);
 64             }
 65             context.SaveChanges();
 66 
 67             var departments = new Department[]
 68             {
 69                 new Department { Name = "English",     Budget = 350000,
 70                     StartDate = DateTime.Parse("2007-09-01"),
 71                     InstructorID  = instructors.Single( i => i.LastName == "Abercrombie").ID },
 72                 new Department { Name = "Mathematics", Budget = 100000,
 73                     StartDate = DateTime.Parse("2007-09-01"),
 74                     InstructorID  = instructors.Single( i => i.LastName == "Fakhouri").ID },
 75                 new Department { Name = "Engineering", Budget = 350000,
 76                     StartDate = DateTime.Parse("2007-09-01"),
 77                     InstructorID  = instructors.Single( i => i.LastName == "Harui").ID },
 78                 new Department { Name = "Economics",   Budget = 100000,
 79                     StartDate = DateTime.Parse("2007-09-01"),
 80                     InstructorID  = instructors.Single( i => i.LastName == "Kapoor").ID }
 81             };
 82 
 83             foreach (Department d in departments)
 84             {
 85                 context.Departments.Add(d);
 86             }
 87             context.SaveChanges();
 88 
 89             var courses = new Course[]
 90             {
 91                 new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3,
 92                     DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID
 93                 },
 94                 new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
 95                     DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID
 96                 },
 97                 new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
 98                     DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID
 99                 },
100                 new Course {CourseID = 1045, Title = "Calculus",       Credits = 4,
101                     DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID
102                 },
103                 new Course {CourseID = 3141, Title = "Trigonometry",   Credits = 4,
104                     DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID
105                 },
106                 new Course {CourseID = 2021, Title = "Composition",    Credits = 3,
107                     DepartmentID = departments.Single( s => s.Name == "English").DepartmentID
108                 },
109                 new Course {CourseID = 2042, Title = "Literature",     Credits = 4,
110                     DepartmentID = departments.Single( s => s.Name == "English").DepartmentID
111                 },
112             };
113 
114             foreach (Course c in courses)
115             {
116                 context.Courses.Add(c);
117             }
118             context.SaveChanges();
119 
120             var officeAssignments = new OfficeAssignment[]
121             {
122                 new OfficeAssignment {
123                     InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID,
124                     Location = "Smith 17" },
125                 new OfficeAssignment {
126                     InstructorID = instructors.Single( i => i.LastName == "Harui").ID,
127                     Location = "Gowan 27" },
128                 new OfficeAssignment {
129                     InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID,
130                     Location = "Thompson 304" },
131             };
132 
133             foreach (OfficeAssignment o in officeAssignments)
134             {
135                 context.OfficeAssignments.Add(o);
136             }
137             context.SaveChanges();
138 
139             var courseInstructors = new CourseAssignment[]
140             {
141                 new CourseAssignment {
142                     CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
143                     InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID
144                     },
145                 new CourseAssignment {
146                     CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
147                     InstructorID = instructors.Single(i => i.LastName == "Harui").ID
148                     },
149                 new CourseAssignment {
150                     CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
151                     InstructorID = instructors.Single(i => i.LastName == "Zheng").ID
152                     },
153                 new CourseAssignment {
154                     CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
155                     InstructorID = instructors.Single(i => i.LastName == "Zheng").ID
156                     },
157                 new CourseAssignment {
158                     CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
159                     InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID
160                     },
161                 new CourseAssignment {
162                     CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
163                     InstructorID = instructors.Single(i => i.LastName == "Harui").ID
164                     },
165                 new CourseAssignment {
166                     CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
167                     InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
168                     },
169                 new CourseAssignment {
170                     CourseID = courses.Single(c => c.Title == "Literature" ).CourseID,
171                     InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
172                     },
173             };
174 
175             foreach (CourseAssignment ci in courseInstructors)
176             {
177                 context.CourseAssignments.Add(ci);
178             }
179             context.SaveChanges();
180 
181             var enrollments = new Enrollment[]
182             {
183                 new Enrollment {
184                     StudentID = students.Single(s => s.LastName == "Alexander").ID,
185                     CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
186                     Grade = Grade.A
187                 },
188                     new Enrollment {
189                     StudentID = students.Single(s => s.LastName == "Alexander").ID,
190                     CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
191                     Grade = Grade.C
192                     },
193                     new Enrollment {
194                     StudentID = students.Single(s => s.LastName == "Alexander").ID,
195                     CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
196                     Grade = Grade.B
197                     },
198                     new Enrollment {
199                         StudentID = students.Single(s => s.LastName == "Alonso").ID,
200                     CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
201                     Grade = Grade.B
202                     },
203                     new Enrollment {
204                         StudentID = students.Single(s => s.LastName == "Alonso").ID,
205                     CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
206                     Grade = Grade.B
207                     },
208                     new Enrollment {
209                     StudentID = students.Single(s => s.LastName == "Alonso").ID,
210                     CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
211                     Grade = Grade.B
212                     },
213                     new Enrollment {
214                     StudentID = students.Single(s => s.LastName == "Anand").ID,
215                     CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
216                     },
217                     new Enrollment {
218                     StudentID = students.Single(s => s.LastName == "Anand").ID,
219                     CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
220                     Grade = Grade.B
221                     },
222                 new Enrollment {
223                     StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
224                     CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
225                     Grade = Grade.B
226                     },
227                     new Enrollment {
228                     StudentID = students.Single(s => s.LastName == "Li").ID,
229                     CourseID = courses.Single(c => c.Title == "Composition").CourseID,
230                     Grade = Grade.B
231                     },
232                     new Enrollment {
233                     StudentID = students.Single(s => s.LastName == "Justice").ID,
234                     CourseID = courses.Single(c => c.Title == "Literature").CourseID,
235                     Grade = Grade.B
236                     }
237             };
238 
239             foreach (Enrollment e in enrollments)
240             {
241                 var enrollmentInDataBase = context.Enrollments.Where(
242                     s =>
243                             s.Student.ID == e.StudentID &&
244                             s.Course.CourseID == e.CourseID).SingleOrDefault();
245                 if (enrollmentInDataBase == null)
246                 {
247                     context.Enrollments.Add(e);
248                 }
249             }
250             context.SaveChanges();
251         }
252     }
253 }

1.7在appsetting.json文件中配置本地数据库连接

1 "ConnectionStrings": {
2     "SchoolContext": "Server=.;Database=ApiDb;user id=sa;password=123456;"
3   }

1.8在Startup.cs文件中配置使用sql server

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3       services.AddDbContext<SchoolContext>(opt =>
 4         opt.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
 5       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 6       services.AddSwaggerGen(c =>
 7       {
 8         c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
 9       });
10 }

 1.9在Program.cs文件中调用测试数据

 1 public class Program
 2 {
 3     public static void Main(string[] args)
 4     {
 5         var host = CreateWebHostBuilder(args).Build();
 6 
 7         using (var scope = host.Services.CreateScope())
 8         {
 9             var services = scope.ServiceProvider;
10             try
11             {
12                 var context = services.GetRequiredService<SchoolContext>();
13                 DbInitializer.Initialize(context);
14             }
15             catch (Exception ex)
16             {
17                 var logger = services.GetRequiredService<ILogger<Program>>();
18                 logger.LogError(ex, "An error occurred while seeding the database.");
19             }
20         }
21 
22         host.Run();
23 }

2. EF数据库迁移

2.1首先在本地数据库,创建一个空的数据库

ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

2.2执行数据库迁移

  保存项目更改,生成项目。然后打开CMD命令窗口,切换到工程目录下,执行以下命令

dotnet ef migrations add ComplexDataModel

2.3更新数据库

  更改数据库后或删除数据库后,在命令窗口运行以下命令

dotnet ef database update

2.4查看数据库

  打开SQL Server Management,查看数据库表生成情况

ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

2.5运行项目,生成测试数据

  测试数据已自动生成

ASP.NET Core创建Web Api项目使用EF自动迁移多表数据库

点赞
收藏
评论区
推荐文章
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
Js可以写桌面应用端?
1、下载nw.jshttps://nwjs.io/最好下载sdk版本。2、解压打开安装包下载完之后,解压打开图中的「app文件夹」是我自己创建的,你也需要自己创建一个,里面放你项目文件。「app文件夹」中一般放一个index.html(页面展示),另外还需要创建一个package.json文件(参数配置):        "name":  "first 
Jacquelyn38 Jacquelyn38
3年前
牛逼!五分钟开发一款桌面版应用
1、下载nw.jshttps://nwjs.io/最好下载sdk版本。2、解压打开安装包下载完之后,解压打开图中的app文件夹是我自己创建的,你也需要自己创建一个,里面放你项目文件。app文件夹中一般放一个index.html(页面展示),另外还需要创建一个package.json文件(参数配置):        "name":  "first  ap
Wesley13 Wesley13
3年前
JAVA多线程测试MQ性能步骤以及代码
1.Windows下安装RabbitMQ需要以下几个步骤  (1):下载erlang,原因在于RabbitMQ服务端代码是使用并发式语言erlang编写的,下载地址:http://www.erlang.org/downloads,双击.exe文件进行安装就好,安装完成之后创建一个名为ERLANG\_HOME的环境变量,其值指向erlang的安装目录,同
Stella981 Stella981
3年前
CentOS 7 安装 libcurl with openssl
最近项目需要重新编译libcurl使其支持ssl,在这里进行记录:下载openssl: curlOLhttps://github.com/openssl/openssl/archive/OpenSSL\_1\_1\_1g.zip创建安装目录:/opt/openssl 配置openssl动态库:./configprefi
Stella981 Stella981
3年前
Asp.net Core 2.1使用 EF Core 简单增删改查操作数据库
Asp.netCore2.1使用EFCore简单增删改查操作数据库大概步骤如下5步:1、创建项目(Asp.netCore2.1项目)2、项目使用EFCore3、建立实体4、生成迁移文件(生成数据库)5、使用VS工具生成视图、控制器代码示例代码下载(https://www.oschina.net/acti
Wesley13 Wesley13
3年前
ubuntu试用docker安装oracle11g
为了简单快速的在ubuntu下面安装一个测试oracle,选择试用docker进行安装下载oracle11g安装包下载oracle11g安装包https://www.oracle.com/database/technologies/oracledatabasesoftwaredo
Stella981 Stella981
3年前
Postman 使用方法详细介绍
1,下载安装:https://www.getpostman.com/apps2,打开Postman,如图所示:!(https://oscimg.oschina.net/oscnet/00f434cd831f2f74fea6f6d7b86bc46a751.png)3,创建一个接口项目!(https://oscimg.oschina.
Stella981 Stella981
3年前
Cesium调用Geoserver发布的 WMS、WFS服务
1GeoServer服务发布1.1WMS服务下载GeoServer安装版安装,同时安装geopackage扩展,以备使用。使用XX地图下载器下载地图,导出成GeoPackage地图文件。(1)下载GeoPackageDEM数据(2)打开GeoServer服务界面!(htt
Stella981 Stella981
3年前
Django内容管理系统(CMS)BVDN环境搭建_mysql数据库安装配置
Mysql安装方式  msi文件安装:msi的安装与常规windows程序安装类似,双击一路默认即可完成安装,此处不再对msi方式安装进行介绍。  zip文件安装:即免安装模式,解压缩后进行简单的设置即可使用。下文以此种安装方式进行Mysql的安装部署。Mysql下载  1、mysql官方下载:https://www.mysq