MySql uses EF Core 2.0 CodeFirst, DbFirst, database Migration (Migration) Introduction and examples, codefirstdbfirst

Source: Internet
Author: User
Tags mysql code

MySql uses EF Core 2.0 CodeFirst, DbFirst, database Migration (Migration) Introduction and examples, codefirstdbfirst

Dotnet core 2.0 has been released for several days. During this period, the MVC project of the original dotnet core 1.1 has also been upgraded to 2.0. the upgrade process is still smooth and there are not many changes. The upgrade of Entity Framwork Core is also indispensable during the upgrade process. This article mainly introduces how to use Entity Framwork Core 2.0 in the MySql Database for Code First, Database First, and Database Migration (Migration ), although it is relatively basic, it should be as detailed as possible. All the sample code in this article has been submitted to GitHub: https://github.com/starts2000/efcoredemo. if you think it is helpful to you, give a Star.

I. Tools and Environment
  • Visual Studio 2017 15.3
  • . Net core 2.0 SDK
Ii. Entity Framwork Core 2.0 MySql Code First and database Migration (Migration) 1. Create the. NET Core class library project Starts2000.EFCoreCodeFirst. 2. Add the User Entity class.
    public class User    {        public int Id { get; set; }        [MaxLength(32), Required]        public string Aaccount { get; set; }        [MaxLength(32), Required]        public string Password { get; set; }    }

The final [Starts2000.EFCoreCodeFirst] project structure is as follows:

 

3. Create the. NET Core console application project Starts2000.EFCoreCodeFirst. Test]
  • Add a reference to the [Starts2000.EFCoreCodeFirst] project;
  • Add Microsoft. EntityFrameworkCore. Tools and Pomelo. EntityFrameworkCore. MySql (Note: including the pre-release version;
4. Edit the Starts2000.EFCoreCodeFirst. Test. csproj project file and add the following content:
<ItemGroup>    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /></ItemGroup>

The final content is as follows:

<Project Sdk="Microsoft.NET.Sdk">  <PropertyGroup>    <TargetFramework>netcoreapp2.0</TargetFramework>    <ApplicationIcon />    <OutputType>Exe</OutputType>    <StartupObject />  </PropertyGroup>  <ItemGroup>    <ProjectReference Include="..\Starts2000.EFCoreCodeFirst\Starts2000.EFCoreCodeFirst.csproj" />  </ItemGroup>  <ItemGroup>    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10058" />  </ItemGroup>  <ItemGroup>    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />  </ItemGroup></Project>
5. Add the TestDbContext class ( Note: Change the database connection string to your own)
    public class TestDbContext : DbContext    {        public DbSet<User> User { get; set; }        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)        {            optionsBuilder.UseMySql(                "server=localhost;database=TestDb;user=test;password=123456;");        }        protected override void OnModelCreating(ModelBuilder modelBuilder)        {            base.OnModelCreating(modelBuilder);            //modelBuilder.Entity<User>().HasIndex(u => u.Aaccount).IsUnique();        }    }
6. Open the command line window, switch to the [Starts2000.EFCoreCodeFirst. Test] project folder directory, and execute the following command:
dotnet ef migrations add InitialCreate

 

If the command is successfully executed, the following content is added to the project directory:

7. Run dotnet ef database update Command

After successful execution, you can see that the database and table are successfully created.

8. Modify the object and update the modified content to the database.

The Account attribute of the User class corresponds to the Account column of the User table, which should be unique. If you forget to set a unique index, add the following in TestDbContext:

    public class TestDbContext : DbContext    {        public DbSet<User> User { get; set; }        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)        {            optionsBuilder.UseMySql(                "server=localhost;database=TestDb;user=test;password=123456;");        }        protected override void OnModelCreating(ModelBuilder modelBuilder)        {            base.OnModelCreating(modelBuilder);            modelBuilder.Entity<User>().HasIndex(u => u.Aaccount).IsUnique();        }    }

Rundotnet ef migrations add UserTableUpdateAccountCommand:

If the command is successfully executed, the following content is added to the project directory:

Next, follow the steps 7. If the operation is successful, you can see that the User table has created the unique index of the Account:

9. Test Data writing and reading

Add the following code to the Main function:

        static void Main(string[] args)        {            using(var context = new TestDbContext())            {                context.User.Add(new Models.User                {                    Aaccount = "CodeFirst-Test-" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),                    Password = "123456"                });                context.SaveChanges();                Console.WriteLine(context.User                    .OrderByDescending(u => u.Id)                    .FirstOrDefault()?.Aaccount);            }            Console.ReadKey();        }

Set the [Starts2000.EFCoreCodeFirst. Test] project as a startup project and compile and run the project:

Iii. Entity Framwork Core 2.0 MySql Database First1. Create the [Starts2000.EFCoreDbFirst] project 2. Add Pomelo. EntityFrameworkCore. MySql ( Note: including the pre-release version3. Edit the Starts2000.EFCoreDbFirst. csproj project file and add the following content:
  <ItemGroup>    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />  </ItemGroup>

The final content is as follows:

<Project Sdk="Microsoft.NET.Sdk">  <PropertyGroup>    <TargetFramework>netcoreapp2.0</TargetFramework>  </PropertyGroup>  <ItemGroup>    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10057" />  </ItemGroup>  <ItemGroup>    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />  </ItemGroup></Project>
4. Open the command line window, switch to the [Starts2000.EFCoreDbFirst] project folder directory, and execute the following command:
dotnet ef dbcontext scaffold "Server=localhost;User Id=test;Password=123456;Database=TestDb" "Pomelo.EntityFrameworkCore.MySql"

After the project is successfully executed, the following content is added to the project:

5. Create the. NET Core console application project Starts2000.EFDbFirst. Test.
  • Add a reference to the [Starts2000.EFCoreDbFirst] project;
  • Modify the Main function to the following code:
        static void Main(string[] args)        {            using (var context = new TestDbContext())            {                context.User.Add(new User                {                    Aaccount = "DbFirst-Test-" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),                    Password = "123456"                });                context.SaveChanges();                Console.WriteLine(context.User                    .OrderByDescending(u => u.Id)                    .FirstOrDefault()?.Aaccount);            }            Console.ReadKey();        }
  • Set the [Starts2000.EFCoreDbFirst. Test] project to start the project and compile and run it:

 

References:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.