EF Core的安装、EF Core与数据库结合

EF Core的安装

EF Core是新一代可扩展和跨平台的Entity
Framework版本。较与旧版本,它不再使用edmx可视化的操作界面,但是仍然可以通过命令的形式通过数据库生成代码或通过代码生成数据库。

EF Core实体框架核心安装:

  1. 工具> NuGet软件包管理器>软件包管理器控制台

  2. Install-Package Microsoft.EntityFrameworkCore.SqlServer

  3. Install-Package Microsoft.EntityFrameworkCore.Tools

  4. Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

数据库与EF结合使用:

方式一:通过现有数据库创建模型:

  1. 工具 - >连接到数据库…,选择Microsoft SQL Server

  2. 添加数据库连接

  3. 工具 - > NuGet软件包管理器 - >软件包管理器控制台

注意:下面的 Server=(localdb)\mssqllocaldb 指的是vs自带的数据库,如果要使用本地SQLServer的话那么需要换成 “.”或 “localhost”。Trusted_Connection=True使用的是window身份验证,如果要使用账户密码的话,请换成Uid和Pwd.

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=[YourDatabase];Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

该命令会在Models文件夹下生成数据库中的表和上下文对象

方式二:通过模型创建数据库

  1. 创建模型类和上下文类

    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions options)
            : base(options)
        { }
    
        public DbSet Blogs { get; set; }
        public DbSet Posts { get; set; }
    }
    
    public class Blog
    {
      public int BlogId { get; set; }
      public string Url { get; set; }
    
      public List< Post > Posts { get; set; }
    }
    
    public class Post
    {
      public int PostId { get; set; }
      public string Title { get; set; }
      public string Content { get; set; }
    
      public int BlogId { get; set; }
      public Blog Blog { get; set; }
    }
  2. 在startup.cs的ConfigureServices方法中中将上下文类注册为全局服务:
    services.AddDbContext(options => options.UseSqlServer(connection));

    在appsetting文件中增加连接字符串connection

  3. 创建数据库
    工具 - > NuGet软件包管理器 - >软件包管理器控制台
    //创建模型的初始表
    Add-Migration InitialCreate
    //将新迁移应用于数据库
    Update-Database

通过模型创建数据库细节

如果选择通过模型创建数据库的方式:

第一步:根据自己预先设计的UML图或类结构关系图,建立模型(model)类

例如图书商城项目中的Book类:

public partial class Book
    {
        public int Id { get; set; }
        public int CategoryId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int PublisherId { get; set; }
        public DateTime PublishDate { get; set; }
        public string Isbn { get; set; }
        public int WordsCount { get; set; }
        public decimal UnitPrice { get; set; }
        public string ContentDescription { get; set; }
        public string AurhorDescription { get; set; }
        public string EditorComment { get; set; }
        public string Toc { get; set; }
    }

第二步:通过Fluent API,创建上下文对象,配置约束

public partial class MallContext : DbContext
{
    public virtual DbSet Book { get; set; }
    public virtual DbSet Captcha { get; set; }
    public virtual DbSet Cart { get; set; }
    //......省略n个模型对象

    //重写OnConfiguring方法,配置数据库连接
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {                    optionsBuilder.UseSqlServer(@"Server=.;Database=Mall;Trusted_Connection=True;");
    }

    //重写OnModelCreating方法,配置创建model的约束条件
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity(entity =>
        {
            entity.Property(e => e.Author)
                  .IsRequired()
                  .HasMaxLength(200);

            entity.Property(e => e.PublishDate).HasColumnType("datetime");

            entity.HasIndex(e => e.Isbn)
                    .HasName("IX_Books_ISBN")
                    .IsUnique();

            entity.Property(e => e.Isbn)
                    .IsRequired()
                    .HasColumnName("ISBN")
                    .HasMaxLength(50);
        }
        modelBuilder.Entity(entity =>
        {
            //......
        }
    }
}

第三步:拥有模型后,通过迁移来创建数据库

工具 - > NuGet软件包管理器 - >软件包管理器控制台

运行 Add-Migration InitialCreate 创建模型的初始表。

运行 Update-Database 以将新迁移应用于数据库。

约束的配置详细

以上面的Book对象为例:

//为某个字段添加索引,并设置索引名,并设为唯一值
entity.HasIndex(e => e.Isbn)
      .HasName("IX_Books_ISBN")
      .IsUnique();

//为某个字段添加约束,设为必填项,字符串最大长度200
entity.Property(e => e.Author)
      .IsRequired()
      .HasMaxLength(200);

//为某个字段添加约束,设为必填项,设置表中列名并与模型类字段建立映射,字符串最大长度为50
 entity.Property(e => e.Isbn)
       .IsRequired()
       .HasColumnName("ISBN")
       .HasMaxLength(50);

//为某个字段添加约束,设置该字段在数据库表中列的Type
entity.Property(e => e.PublishDate).HasColumnType("datetime");

//为某个字段建立与表中列名的映射,并设置默认值
entity.Property(e => e.Toc)
      .HasColumnName("TOC")
      .HasDefaultValueSql("0");

entity.Property(e => e.Title)
      .IsRequired()
      .HasMaxLength(200);

entity.Property(e => e.UnitPrice).HasColumnType("money");

你可能感兴趣的:(.Net,.NET,Core)