首页 .Net .NET Core Mysql EF Core中通过dotnet命令Code First创建生成数据库

.NET Core Mysql EF Core中通过dotnet命令Code First创建生成数据库

1、为此示例创建一个控制台应用程序

1) 使用.NET Core命令行界面(CLI)初始化有效的.NET Core项目和控制台应用程序,然后切换到新创建的文件夹(mysqlefcore)

dotnet new console –o mysqlefcore
cd mysqlefcore

2) MySql.Data.EntityFrameworkCore 使用CLI 将包添加到应用程序

dotnet add package MySql.Data.EntityFrameworkCore --version 6.10.8

或者,您可以使用Visual Studio中的程序包管理器控制台添加程序包:

Install-Package MySql.Data.EntityFrameworkCore -Version 6.10.8

注意
版本(例如6.10.8)必须与您使用的实际Connector / NET版本匹配。有关当前版本信息,请参阅表9.2“支持的Entity Framework Core版本”

3) 恢复项目文件中指定的依赖项和项目特定工具

dotnet restore

2、创建模型并运行应用程序

控制器应用程序将使用此EF Core示例中的模型。它由两个与书库相关的实体组成,这些实体将在 LibraryContext类(或数据库上下文)中配置。

1) 创建一个名为的新文件LibraryModel.cs,然后将以下Book和Publisher类添加到mysqlefcore命名空间

namespace mysqlefcore
{
public >Book
{
public string ISBN { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Language { get; set; }
public int Pages { get; set; }
public virtual Publisher Publisher { get; set; }
}
public >Publisher
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}

2) 创建一个名为的新文件LibraryContext.cs并添加后面的代码。将通用连接字符串替换为适合MySQL服务器配置的字符串

该LibraryContext >using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;
namespace mysqlefcore
{
public >LibraryContext : DbContext
{
public DbSet<Book> Book { get; set; }
public DbSet<Publisher> Publisher { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;database=library;user=user;password=password");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Publisher>(entity =>
{
entity.HasKey(e => e.ID);
entity.Property(e => e.Name).IsRequired();
});
modelBuilder.Entity<Book>(entity =>
{
entity.HasKey(e => e.ISBN);
entity.Property(e => e.Title).IsRequired();
entity.HasOne(d => d.Publisher)
.WithMany(p => p.Books);
});
}
}
}

3) 将以下代码插入现有Program.cs文件,替换默认的C#代码

using Microsoft.EntityFrameworkCore;
using System;
using System.Text;
namespace mysqlefcore
{
  >Program
  {
    static void Main(string[] args)
    {
      InsertData();
      PrintData();
    }
    private static void InsertData()
    {
      using(var context = new LibraryContext())
      {
        // Creates the database if not exists
        context.Database.EnsureCreated();
        // Adds a publisher
        var publisher = new Publisher
        {
          Name = "Mariner Books"
        };
        context.Publisher.Add(publisher);
        // Adds some books
        context.Book.Add(new Book
        {
          ISBN = "978-0544003415",
          Title = "The Lord of the Rings",
          Author = "J.R.R. Tolkien",
          Language = "English",
          Pages = 1216,
          Publisher = publisher
        });
        context.Book.Add(new Book
        {
          ISBN = "978-0547247762",
          Title = "The Sealed Letter",
          Author = "Emma Donoghue",
          Language = "English",
          Pages = 416,
          Publisher = publisher
        });
        // Saves changes
        context.SaveChanges();
      }
    }
    private static void PrintData()
    {
      // Gets and prints all books in database
      using (var context = new LibraryContext())
      {
        var books = context.Book
          .Include(p => p.Publisher);
        foreach(var book in books)
        {
          var data = new StringBuilder();
          data.AppendLine($"ISBN: {book.ISBN}");
          data.AppendLine($"Title: {book.Title}");
          data.AppendLine($"Publisher: {book.Publisher.Name}");
          Console.WriteLine(data.ToString());
        }
      }
    }
  }
}

4) 使用以下CLI命令还原依赖项,然后运行该应用程序

dotnet restore
dotnet run

运行应用程序的输出

ISBN: 978-0544003415
Title: The Lord of the Rings
Publisher: Mariner Books
ISBN: 978-0547247762
Title: The Sealed Letter
Publisher: Mariner Books

参考文档https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-example.html


特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。