应无所住,而生其心
排名
1
文章
860
粉丝
112
评论
163
net core webapi post传递参数
庸人 : 确实坑哈,我也是下班好了好几次,发现后台传递对象是可以的,但...
百度编辑器自定义模板
庸人 : 我建议换个编辑器,因为现在百度富文本已经停止维护了,用tinymec...
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

Core EF Code First-黑色主题效果

6361人阅读 2020/12/18 16:27 总访问:5203668 评论:0 收藏:0 手机
分类: .NET Core


创建好实体

Student类:

  1. public class Student
  2. {
  3. public int ID { get; set; }
  4. public string LastName { get; set; }
  5. public string FirstMidName { get; set; }
  6. public DateTime EnrollmentDate { get; set; }
  7. public ICollection<Enrollment> Enrollments { get; set; }
  8. }

Course类:

  1. public class Course
  2. {
  3. [DatabaseGenerated(DatabaseGeneratedOption.None)]
  4. public int CourseID { get; set; }
  5. public string Title { get; set; }
  6. public int Credits { get; set; }
  7. public ICollection<Enrollment> Enrollments { get; set; }
  8. }

Enrollment类:

  1. public enum Grade
  2. {
  3. A, B, C, D, F
  4. }
  5. public class Enrollment
  6. {
  7. public int EnrollmentID { get; set; }
  8. public int CourseID { get; set; }
  9. public int StudentID { get; set; }
  10. public Grade? Grade { get; set; }
  11. public Course Course { get; set; }
  12. public Student Student { get; set; }
  13. }

创建数据库上下文

使得给定的数据模型与 Entity Framework 功能相协调的主类是数据库上下文类。 可以通过继承 Microsoft.EntityFrameworkCore.DbContext 类的方式创建此类。 在该类中你可以指定数据模型中包含哪些实体

  1. public class SchoolContext : DbContext
  2. {
  3. public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
  4. {
  5. }
  6. public DbSet<Course> Courses { get; set; }
  7. public DbSet<Enrollment> Enrollments { get; set; }
  8. public DbSet<Student> Students { get; set; }
  9. }

当数据库创建完成后, EF 创建一系列数据表,表名默认和 DbSet 属性名相同。 集合属性的名称一般使用复数形式,但不同的开发人员的命名习惯可能不一样,开发人员根据自己的情况确定是否使用复数形式

  1. public class SchoolContext : DbContext
  2. {
  3. public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
  4. {
  5. }
  6. public DbSet<Course> Courses { get; set; }
  7. public DbSet<Enrollment> Enrollments { get; set; }
  8. public DbSet<Student> Students { get; set; }
  9. protected override void OnModelCreating(ModelBuilder modelBuilder)
  10. {
  11. modelBuilder.Entity<Course>().ToTable("Course");
  12. modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
  13. modelBuilder.Entity<Student>().ToTable("Student");
  14. }
  15. }

注册 SchoolContext

ASP.NET Core 默认实现 依赖注入。 在应用程序启动过程通过依赖注入注册相关服务 (例如 EF 数据库上下文)

  1. services.AddDbContext<SchoolContext>(options =>
  2. options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

打开 appsettings.json 文件,并按以下所示添加连接字符串。

  1. {
  2. "ConnectionStrings": {
  3. "SchoolContext": "Server=.;Database=SchoolContext;uid=sa;password=123456",
  4. "SchoolContext2": "Server=(localdb)\\mssqllocaldb;Database=SchoolContext;Trusted_Connection=True;
  5. MultipleActiveResultSets=true"
  6. }
  7. }

数据库连接字符串可以使用指定使用 SQL Server LocalDB 数据库。 LocalDB 是 SQL Server Express 数据库引擎的轻量级版本,用于应用程序开发,不在生产环境中使用。 LocalDB 作为按需启动并在用户模式下运行的轻量级数据库没有复杂的配置。 默认情况下, LocalDB 在 C:/Users/目录下创建 .mdf 数据库文件。

初始化数据库

  1. public static class DbInitializer
  2. {
  3. public static void Initialize(SchoolContext context)
  4. {
  5. var isscuess = context.Database.EnsureCreated();
  6. // Look for any students.
  7. if (context.Students.Any())
  8. {
  9. return; // DB has been seeded
  10. }
  11. var students = new Student[]
  12. {
  13. new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
  14. new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
  15. new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
  16. new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
  17. new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
  18. new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
  19. new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
  20. new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
  21. };
  22. foreach (Student s in students)
  23. {
  24. context.Students.Add(s);
  25. }
  26. context.SaveChanges();
  27. var courses = new Course[]
  28. {
  29. new Course{CourseID=1050,Title="Chemistry",Credits=3},
  30. new Course{CourseID=4022,Title="Microeconomics",Credits=3},
  31. new Course{CourseID=4041,Title="Macroeconomics",Credits=3},
  32. new Course{CourseID=1045,Title="Calculus",Credits=4},
  33. new Course{CourseID=3141,Title="Trigonometry",Credits=4},
  34. new Course{CourseID=2021,Title="Composition",Credits=3},
  35. new Course{CourseID=2042,Title="Literature",Credits=4}
  36. };
  37. foreach (Course c in courses)
  38. {
  39. context.Courses.Add(c);
  40. }
  41. context.SaveChanges();
  42. var enrollments = new Enrollment[]
  43. {
  44. new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
  45. new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
  46. new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
  47. new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
  48. new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
  49. new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
  50. new Enrollment{StudentID=3,CourseID=1050},
  51. new Enrollment{StudentID=4,CourseID=1050},
  52. new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
  53. new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
  54. new Enrollment{StudentID=6,CourseID=1045},
  55. new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
  56. };
  57. foreach (Enrollment e in enrollments)
  58. {
  59. context.Enrollments.Add(e);
  60. }
  61. context.SaveChanges();
  62. }
  63. }

在 Program.cs,修改 Main 方法,使得在应用程序启动时能执行以下操作:

  1. using ContosoUniversity.Data;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.Extensions.Hosting;
  5. using Microsoft.Extensions.Logging;
  6. using System;
  7. namespace ContosoUniversity
  8. {
  9. public class Program
  10. {
  11. public static void Main(string[] args)
  12. {
  13. var host = CreateHostBuilder(args).Build();
  14. CreateDbIfNotExists(host);
  15. host.Run();
  16. }
  17. private static void CreateDbIfNotExists(IHost host)
  18. {
  19. using (var scope = host.Services.CreateScope())
  20. {
  21. var services = scope.ServiceProvider;
  22. try
  23. {
  24. var context = services.GetRequiredService<SchoolContext>();
  25. DbInitializer.Initialize(context);
  26. }
  27. catch (Exception ex)
  28. {
  29. var logger = services.GetRequiredService<ILogger<Program>>();
  30. logger.LogError(ex, "An error occurred creating the DB.");
  31. }
  32. }
  33. }
  34. public static IHostBuilder CreateHostBuilder(string[] args) =>
  35. Host.CreateDefaultBuilder(args)
  36. .ConfigureWebHostDefaults(webBuilder =>
  37. {
  38. webBuilder.UseStartup<Startup>();
  39. });
  40. }
  41. }

EF CORE读取数据

我们这里可以使用异步的方式来读取与返回数据

  1. public async Task<IActionResult> Index()
  2. {
  3. return View(await _context.Students.ToListAsync());
  4. }

view页面中razor解析数据

  1. @model IEnumerable<Learn.Models.Student>
  2. @{
  3. ViewData["Title"] = "Index";
  4. }
  5. <h1>Index</h1>
  6. <form>
  7. <p>
  8. <a asp-action="Create">Create New</a>
  9. <input type="text" name="firstMidName" value="@ViewBag.firstMidName" />
  10. <input type="submit" value="查询" />
  11. </p>
  12. </form>
  13. <table class="table">
  14. <thead>
  15. <tr>
  16. <th>
  17. @Html.DisplayNameFor(model => model.LastName)
  18. </th>
  19. <th>
  20. @Html.DisplayNameFor(model => model.FirstMidName)
  21. </th>
  22. <th>
  23. @Html.DisplayNameFor(model => model.EnrollmentDate)
  24. </th>
  25. <th></th>
  26. </tr>
  27. </thead>
  28. <tbody>
  29. @foreach (var item in Model)
  30. {
  31. <tr>
  32. <td>
  33. @Html.DisplayFor(modelItem => item.LastName)
  34. </td>
  35. <td>
  36. @Html.DisplayFor(modelItem => item.FirstMidName)
  37. </td>
  38. <td>
  39. @Html.DisplayFor(modelItem => item.EnrollmentDate)
  40. </td>
  41. <td>
  42. <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
  43. <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
  44. <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
  45. </td>
  46. </tr>
  47. }
  48. </tbody>
  49. </table>

欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价

NET core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

.net mvc分部页,.net core分部页

.net分部页的三种方式第一种:@Html.Partial(&quot;_分部页&quot;)第二种:@{ Html.RenderPartial(&quot;分部页&quot;);}...

StackExchange.Redis操作redis(net core支持)

官方git开源地址https://github.com/StackExchange/StackExchange.Redis官方文档在docs里边都是官方的文档通过nuget命令下...

.net core 使用session

tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了使用nuget添加引用Microsoft.AspN...

通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET core?

朋友圈@蓝羽 看到一篇文章写的太详细太通俗了,搬过来细细看完,保证你对.NET有个新的认识理解原文地址:https://www.cnblo...

asp.net core2.0 依赖注入 AddTransient与AddScoped的区别

asp.net core主要提供了三种依赖注入的方式其中AddTransient与AddSingleton比较好区别AddTransient瞬时模式:每次都获取一...

.NET core 使用 Kestrel

Kestrel介绍 Kestrel是一个基于libuv的跨平台web服务器 在.net core项目中就可以不一定要发布在iis下面了Kestrel体验可以使...

Net core中使用cookie

net core中可以使用传统的cookie也可以使用加密的cookieNET CORE中使用传统cookie设置:HttpContext.Response.Cookies.Appe...

NET core项目结构简单分析

一:wwwrootwwwroot用于存放网站的静态资源,例如css,js,图片与相关的前端插件等lib主要是第三方的插件,例如微软默认引用...

Net core使用EF之DB First

一.新建一个.net core的MVC项目新建好项目后,不能像以前一样直接在新建项中添加ef了,需要用命令在添加ef的依赖二.使用Nug...

.net core使用requestresponse下载文件下载excel等

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

iframe自适应高度与配合net core使用

去掉iframe边框frameborder=&quot;0&quot;去掉滚动条scrolling=&quot;no&quot;iframe 自适应高度如果内容是固定的,那么就...

net core启动报错Unable to configure HTTPS endpoint. No server certificate was specified

这是因为net core2.1默认使用的https,如果使用Kestrel web服务器的话没有安装证书就会报这个错其实仔细看他的错误提示,其...

net core中使用url编码与解码操作

net core中暂时还没有以前asp.net与mvc中的server对象。获取url的编码与解码操作不能使用以前的server对象来获取。使用的是...

下载net core

官方下载地址:https://dotnet.microsoft.com/download 进来之后就可以看到最新的下载版本可以直接点击下载,也可以下载其...