当前位置:   article > 正文

.Net C# 使用 EF Core_c#大型项目使用efcore学习

c#大型项目使用efcore学习

使用ORM框架可以加快开发速度,现在简单说下在.Net开发中使用微软官方提供的ORM框架

Entity Framework Core初始化数据库及数据表上手用法。

首先引入依赖项,通过Nuget服务添加如下3个包,因为当前使用的SQL Server数据库所以引入的是SQL Server扩展,根据数据库不同添加不同数据库的扩展即可。EF Core已经屏蔽了大部分数据库的差异。

1.添加依赖项:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer

2.创建实体类

  1. /// <summary>
  2. /// 作者
  3. /// </summary>
  4. public class Author
  5. {
  6. public long Id { get; set; }
  7. public string Name { get; set; }
  8. public Sex Sex { get; set; }
  9. public string Email { get; set; }
  10. public string Phone { get; set; }
  11. public DateTime Birthday { get; set; }
  12. public IEnumerable<Book> Books { get; set; }
  13. }

  1. /// <summary>
  2. /// 书籍
  3. /// </summary>
  4. public class Book
  5. {
  6. public long Id { get; set; }
  7. public string Name { get; set; }
  8. public Category Category { get; set; }
  9. public IEnumerable<Page> Pages { get; set; }
  10. public long AuthorId { get; set; }
  11. public Author Author { get; set; }
  12. }

  1. /// <summary>
  2. /// 分类
  3. /// </summary>
  4. public class Category
  5. {
  6. public long Id { get; set; }
  7. public string Name { get; set; }
  8. }

  1. /// <summary>
  2. /// 书籍内容页
  3. /// </summary>
  4. public class Page
  5. {
  6. public long Id { get; set; }
  7. public string Content { get; set; }
  8. public string Title { get; set; }
  9. public string Description { get; set; }
  10. public int PageNumber { get; set; }
  11. public long BookId { get; set; }
  12. public Book Book { get; set; }
  13. }

  1. /// <summary>
  2. /// 性别枚举
  3. /// </summary>
  4. public enum Sex
  5. {
  6. Male,
  7. Female,
  8. Other
  9. }

3.创建实体配置类(Fluent API)

  1. public class AuthorConfig : IEntityTypeConfiguration<Author>
  2. {
  3. public void Configure(EntityTypeBuilder<Author> builder)
  4. {
  5. builder.ToTable("Author").HasKey(x => x.Id);//配置表名称及设置主键
  6. builder.Property(x => x.Name).HasMaxLength(50).IsRequired().HasComment("作者名称");//配置字段名称及长度、是否必填、注释
  7. builder.Property(x => x.Birthday).HasDefaultValueSql("getdate()").HasComment("出生日期");//配置字段默认值、注释
  8. builder.Property(x => x.Email).HasMaxLength(100).IsRequired(false).HasComment("邮箱");//配置字段长度、是否必填、注释
  9. builder.Property(x => x.Phone).HasMaxLength(20).IsRequired(false).HasComment("电话");//配置字段长度、是否必填、注释
  10. builder.Property(x => x.Sex).HasConversion<int>().HasComment("性别");// 为枚举类型的配置、配置枚举类型的转换方式、配置注释
  11. builder.HasMany(t => t.Books).WithOne(t => t.Author).HasForeignKey(t => t.AuthorId);//配置一对多关系
  12. }
  13. }

  1. public class BookConfig : IEntityTypeConfiguration<Book>
  2. {
  3. public void Configure(EntityTypeBuilder<Book> builder)
  4. {
  5. builder.ToTable("Book").HasKey(x => x.Id);//配置表名称及设置主键
  6. builder.Property(x => x.Name).HasMaxLength(50).IsRequired().HasComment("书籍名称");//配置字段名称及长度、是否必填、注释
  7. builder.HasMany(t => t.Pages).WithOne(t => t.Book).HasForeignKey(t => t.BookId);//配置一对多关系
  8. builder.HasOne(t => t.Category).WithMany();//配置单向导航
  9. }
  10. }

  1. public class CategoryConfig : IEntityTypeConfiguration<Category>
  2. {
  3. public void Configure(EntityTypeBuilder<Category> builder)
  4. {
  5. builder.ToTable("Category").HasKey(x => x.Id);//配置表名称及设置主键
  6. builder.Property(x => x.Name).HasMaxLength(50).IsRequired().HasComment("分类名称");//配置字段名称及长度、是否必填、注释
  7. }
  8. }
  1. public class PageConfig : IEntityTypeConfiguration<Page>
  2. {
  3. public void Configure(EntityTypeBuilder<Page> builder)
  4. {
  5. builder.ToTable("Page").HasKey(x => x.Id);//配置表名称及设置主键
  6. builder.Property(x => x.Content).HasMaxLength(200).IsRequired().HasComment("内容");//配置字段名称及长度、是否必填、注释
  7. builder.Property(x => x.BookId).HasComment("书籍Id");//配置字段名称及长度、是否必填、注释
  8. builder.Property(x => x.PageNumber).HasComment("页码");//配置字段名称及长度、是否必填、注释
  9. builder.Property(x => x.Title).HasMaxLength(50).IsRequired().HasComment("标题");//配置字段名称及长度、是否必填、注释
  10. }
  11. }

4.创建DbContext类

  1. public class BookDbContext : DbContext
  2. {
  3. public DbSet<Author> Authors { get; set; }
  4. public DbSet<Book> Books { get; set; }
  5. public DbSet<Category> Categories { get; set; }
  6. public DbSet<Page> Pages { get; set; }
  7. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  8. {
  9. base.OnConfiguring(optionsBuilder);
  10. optionsBuilder.UseSqlServer(
  11. @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EFCoreDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  12. );//配置数据库连接,因为是控制台项目所以在这里写了,正确使用请使用依赖注入
  13. }
  14. }

5.初始化数据库及表

在程序包管理控制台中执行如下命令:

Add-Migration Init

会生成如下内容: 

  1. public partial class Init : Migration
  2. {
  3. protected override void Up(MigrationBuilder migrationBuilder)
  4. {
  5. migrationBuilder.CreateTable(
  6. name: "Authors",
  7. columns: table => new
  8. {
  9. Id = table.Column<long>(type: "bigint", nullable: false)
  10. .Annotation("SqlServer:Identity", "1, 1"),
  11. Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
  12. Sex = table.Column<int>(type: "int", nullable: false),
  13. Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
  14. Phone = table.Column<string>(type: "nvarchar(max)", nullable: false),
  15. Birthday = table.Column<DateTime>(type: "datetime2", nullable: false)
  16. },
  17. constraints: table =>
  18. {
  19. table.PrimaryKey("PK_Authors", x => x.Id);
  20. });
  21. migrationBuilder.CreateTable(
  22. name: "Categories",
  23. columns: table => new
  24. {
  25. Id = table.Column<long>(type: "bigint", nullable: false)
  26. .Annotation("SqlServer:Identity", "1, 1"),
  27. Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
  28. },
  29. constraints: table =>
  30. {
  31. table.PrimaryKey("PK_Categories", x => x.Id);
  32. });
  33. migrationBuilder.CreateTable(
  34. name: "Books",
  35. columns: table => new
  36. {
  37. Id = table.Column<long>(type: "bigint", nullable: false)
  38. .Annotation("SqlServer:Identity", "1, 1"),
  39. Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
  40. CategoryId = table.Column<long>(type: "bigint", nullable: false),
  41. AuthorId = table.Column<long>(type: "bigint", nullable: false)
  42. },
  43. constraints: table =>
  44. {
  45. table.PrimaryKey("PK_Books", x => x.Id);
  46. table.ForeignKey(
  47. name: "FK_Books_Authors_AuthorId",
  48. column: x => x.AuthorId,
  49. principalTable: "Authors",
  50. principalColumn: "Id",
  51. onDelete: ReferentialAction.Cascade);
  52. table.ForeignKey(
  53. name: "FK_Books_Categories_CategoryId",
  54. column: x => x.CategoryId,
  55. principalTable: "Categories",
  56. principalColumn: "Id",
  57. onDelete: ReferentialAction.Cascade);
  58. });
  59. migrationBuilder.CreateTable(
  60. name: "Pages",
  61. columns: table => new
  62. {
  63. Id = table.Column<long>(type: "bigint", nullable: false)
  64. .Annotation("SqlServer:Identity", "1, 1"),
  65. Content = table.Column<string>(type: "nvarchar(max)", nullable: false),
  66. Title = table.Column<string>(type: "nvarchar(max)", nullable: false),
  67. Description = table.Column<string>(type: "nvarchar(max)", nullable: false),
  68. PageNumber = table.Column<int>(type: "int", nullable: false),
  69. BookId = table.Column<long>(type: "bigint", nullable: false)
  70. },
  71. constraints: table =>
  72. {
  73. table.PrimaryKey("PK_Pages", x => x.Id);
  74. table.ForeignKey(
  75. name: "FK_Pages_Books_BookId",
  76. column: x => x.BookId,
  77. principalTable: "Books",
  78. principalColumn: "Id",
  79. onDelete: ReferentialAction.Cascade);
  80. });
  81. migrationBuilder.CreateIndex(
  82. name: "IX_Books_AuthorId",
  83. table: "Books",
  84. column: "AuthorId");
  85. migrationBuilder.CreateIndex(
  86. name: "IX_Books_CategoryId",
  87. table: "Books",
  88. column: "CategoryId");
  89. migrationBuilder.CreateIndex(
  90. name: "IX_Pages_BookId",
  91. table: "Pages",
  92. column: "BookId");
  93. }
  94. protected override void Down(MigrationBuilder migrationBuilder)
  95. {
  96. migrationBuilder.DropTable(
  97. name: "Pages");
  98. migrationBuilder.DropTable(
  99. name: "Books");
  100. migrationBuilder.DropTable(
  101. name: "Authors");
  102. migrationBuilder.DropTable(
  103. name: "Categories");
  104. }
  105. }

执行如下命令应用到数据库: 

Update-Database

结果如下:

 通过以上操作到最终生成数据库及相关数据表整个流程很快,使用体验很好。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/666155
推荐阅读
相关标签
  

闽ICP备14008679号