您现在的位置是:首页 >其他 >.Net C# 使用 EF Core网站首页其他

.Net C# 使用 EF Core

一个堆栈 2024-06-17 10:43:16
简介.Net C# 使用 EF Core

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

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

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

1.添加依赖项:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer

2.创建实体类

    /// <summary>
    /// 作者
    /// </summary>
    public class Author
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public Sex Sex { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public DateTime Birthday { get; set; }
        public IEnumerable<Book> Books { get; set; }

    }

    /// <summary>
    /// 书籍
    /// </summary>
    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public Category Category { get; set; }
        public IEnumerable<Page> Pages  { get; set; }
        public long AuthorId { get; set; }
        public Author Author { get; set; }
    }

    /// <summary>
    /// 分类
    /// </summary>
    public class Category
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }

    /// <summary>
    /// 书籍内容页
    /// </summary>
    public class Page
    {
        public long Id { get; set; }
        public string Content { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int PageNumber { get; set; }
        public long BookId { get; set; }
        public Book Book { get; set; }
    }

    /// <summary>
    /// 性别枚举
    /// </summary>
    public enum Sex
    {
        Male,
        Female,
        Other
    }

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

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

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

        }
    }

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

4.创建DbContext类

    public class BookDbContext : DbContext
    {
        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Page> Pages { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(
                               @"Data Source=(localdb)MSSQLLocalDB;Initial Catalog=EFCoreDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
                );//配置数据库连接,因为是控制台项目所以在这里写了,正确使用请使用依赖注入
        }
    }

5.初始化数据库及表

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

Add-Migration Init

会生成如下内容: 

public partial class Init : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Authors",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Sex = table.Column<int>(type: "int", nullable: false),
                    Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Phone = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Birthday = table.Column<DateTime>(type: "datetime2", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Authors", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Categories",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Categories", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Books",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    CategoryId = table.Column<long>(type: "bigint", nullable: false),
                    AuthorId = table.Column<long>(type: "bigint", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Books", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Books_Authors_AuthorId",
                        column: x => x.AuthorId,
                        principalTable: "Authors",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_Books_Categories_CategoryId",
                        column: x => x.CategoryId,
                        principalTable: "Categories",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "Pages",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Content = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Title = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    PageNumber = table.Column<int>(type: "int", nullable: false),
                    BookId = table.Column<long>(type: "bigint", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Pages", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Pages_Books_BookId",
                        column: x => x.BookId,
                        principalTable: "Books",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Books_AuthorId",
                table: "Books",
                column: "AuthorId");

            migrationBuilder.CreateIndex(
                name: "IX_Books_CategoryId",
                table: "Books",
                column: "CategoryId");

            migrationBuilder.CreateIndex(
                name: "IX_Pages_BookId",
                table: "Pages",
                column: "BookId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Pages");

            migrationBuilder.DropTable(
                name: "Books");

            migrationBuilder.DropTable(
                name: "Authors");

            migrationBuilder.DropTable(
                name: "Categories");
        }
    }

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

Update-Database

结果如下:

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

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。