Location>code7788 >text

Using EF to connect to databases SQLserver, MySql to implement CodeFirst.

Popularity:922 ℃/2024-07-20 23:55:22

1. Create a new project, download the Nuget installation package

There are a few things to note when creating a project. If the project is based on the .net framework, you need to select the corresponding version of EF, and if it is cross-platform, you need to select the EF Core version.

I have chosen the .net framework version here. In the red box are the packages needed to implement EF Code First.

Corresponding version:

EntityFramework 6.3.0

6.8.8

6.8.3 

If you are connecting to SqlServer, it's easy to download EntityFramework 6.3.0 directly. The program will introduce these two components. Then you can write the code.

 

For MySQL, you need to download these two packages again

 

 

After the download is complete, set up or File This step is usually added automatically when the package is downloaded, but if not, add it manually.

  <entityFramework>
    <providers>
    <provider invariantName="" type=", " />
    <provider invariantName="" type=", .EF6, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>

2. Create EFModel

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace 
{
    [Table("BaseDevice")]
    public class BaseDevice
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public class BaseDeviceDbContext : DbContext
    {
        public BaseDeviceDbContext()
           : base("myConn")
        {
            (new DropCreateDatabaseIfModelChanges<BaseDeviceDbContext>());
        }

        public DbSet<BaseDevice> BaseDevice { get; set; }
    }
}

4. Operate the database Test

        /// <summary>
        /// code first 
        /// </summary>
        public static void TestCodeFirst()
        {
            using (var context = new BaseDeviceDbContext())
            {
                // Query Data
              List<BaseDevice> models = ();

                // Add Data
                (new BaseDevice { Id = 1, Name = "New Model", Description= "Description" });
                (new BaseDevice { Id = 3, Name = "New Model", Description = "Description" });
                ();

                //// Update data
                var model = (m =>  == 1);
                if (model != null)
                {
                     = "Updated Name";
                    ();
                }

                // Delete data
                (model);
                ();
            }
        }