.NET Framework 4.8 console application in C# accesses the established database through EF

Table of Contents

1. Create a .NET Framework 4.8 console application

2. Establish a database

1. Establish database Blogging in SSMS

2. Create a new database connection on VS

3. Install the EF package

4. Automatically generate EF models and contexts

1.Blog.cs class model

2. Model of Post.cs class

3.BloggingContext.cs database context

5. Write an application


We all know that the last updated version of .NET Framework was 4.8.1, but the EF version that once supported .NET Framework has been updated to this day and is still innovating. The current mainstream VS2022 still supports .NET Framework 4.8. When using EF to access the database under .NET Framework 4.8, it is impossible to directly use the default installation of VS2022 without some additional operations. Fortunately, VS2022 does not close the door to using EF to access the database under .NET Framework 4.8. The author has studied, compiled and published this article to provide it to those in need.

The core content of this article is: Find and install the appropriate and supported EF version for .NET Framework 4.8 in VS2022. Only suitable EF versions support .NET Framework 4.8 accessing databases through EF.

1. Create a .NET Framework 4.8 console application

How to create it is omitted here.

2. Create database

1. Create database Blogging in SSMS

Create a new database, create a new query, paste the following database source code, and execute.

CREATE DATABASE [Blogging];
GO

USE [Blogging];
GO

CREATE TABLE [Blog] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO

CREATE TABLE [Post] (
    [PostId] int NOT NULL IDENTITY,
    [BlogId] int NOT NULL,
    [Content] nvarchar(max),
    [Title] nvarchar(max),
    CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
    CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO

INSERT INTO [Blog] (Url) VALUES
('http://blogs.msdn.com/dotnet'),
('http://blogs.msdn.com/webdev'),
('http://blogs.msdn.com/visualstudio')
GO

2. Create a new database connection on VS

In the above new project, create a new database connection and connect to the database Blogging. How to establish this connection is omitted here.

Data Source=DESKTOP-3LV13FS;Initial Catalog=Blogging;Integrated Security=True

3. Install EF package

Finding the program package suitable for .NET Framework 4.8 version and installing it are the key points for the establishment of this method. After some testing and information review by the author, the most suitable EF version is 3.1.32. No higher version than this supports .NET Framework. Packages that should be installed:

  • NuGet Gallery | Microsoft.EntityFrameworkCore 3.1.32

NuGet\Install-Package Microsoft.EntityFrameworkCore -Version 3.1.32

  • NuGet Gallery | Microsoft.EntityFrameworkCore.SqlServer 3.1.32

NuGet\Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.32

  • NuGet Gallery | Microsoft.EntityFrameworkCore.Design 3.1.32

NuGet\Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.1.32

  • NuGet Gallery | Microsoft.EntityFrameworkCore.Tools 3.1.32

NuGet\Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.32

Installation method: VS2022 above project page form → Tools → NuGet Package Manager → Package Manager Console → Copy and paste the blue text above into the console after PM>, press Enter, and wait. Observe the resource manager on the right and add references one by one.

After the installation is successful, there is no red warning message in the package manager console, and there is a prompt that the installation is successful. You can also check App.config to see if the installation was successful.

//App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Caching.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

4. Automatically generate EF model and context

EF models and contexts for accessing existing databases can be automatically generated programmatically.

PM> Scaffold-DbContext "Server=DESKTOP-3LV13FS;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer
Build started...
Build succeeded.
PM> 

The resource manager on the right automatically generates and maps the Blog.cs class model, Post.cs class model (the database has several columns, automatically generates several class models), and the BloggingContext.cs database context.

1.Blog.cs class model

//Blog EF model
using System;
using System.Collections.Generic;

// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable

namespace_10_8
{
    public partial class Blog
    {
        publicBlog()
        {
            Post = new HashSet<Post>();
        }

        public int BlogId { get; set; }
        public string Url { get; set; }

        public virtual ICollection<Post> Post { get; set; }
    }
}

2.Post.cs class model

//Post EF model
using System;
using System.Collections.Generic;

// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable

namespace_10_8
{
    public partial class Post
    {
        public int PostId { get; set; }
        public int BlogId { get; set; }
        public string Content { get; set; }
        public string Title { get; set; }

        public virtual Blog Blog { get; set; }
    }
}

3.BloggingContext.cs database context

//Context of DbContext class
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable

namespace_10_8
{
    public partial class BloggingContext : DbContext
    {
        publicBloggingContext()
        {
        }

        public BloggingContext(DbContextOptions<BloggingContext> options)
            :base(options)
        {
        }

        public virtual DbSet<Blog> Blog { get; set; }
        public virtual DbSet<Post> Post { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Server=DESKTOP-3LV13FS;Database=Blogging;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>(entity =>
            {
                entity.Property(e => e.Url).IsRequired();
            });

            modelBuilder.Entity<Post>(entity =>
            {
                entity.HasOne(d => d.Blog)
                    .WithMany(p => p.Post)
                    .HasForeignKey(d => d.BlogId);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

Five. Let’s write an application

What do you want this program to do? Start writing your application now: add a new URL to the Blog through the application and output it to the console.

//Add a record to the existing database through EF under .NET Framework 4.8
//Add a record to the existing database through EF under .NET Framework 4.8
using System;
using static System.Net.WebRequestMethods;

namespace_10_8
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                db.Blog.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                var count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);

                Console.WriteLine();
                Console.WriteLine("All blogs in database:");
                foreach (var blog in db.Blog)
                {
                    Console.WriteLine(" - {0}", blog.Url);
                }
            }
        }
    }
}   //operation result:
/*
1 records saved to database

All blogs in database:
 -http://blogs.msdn.com/dotnet
 -http://blogs.msdn.com/webdev
 -http://blogs.msdn.com/visualstudio
 -http://blogs.msdn.com/adonet
Please press any key to continue. . .*/

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. MySQL entry-level skills treeHomepageOverview 78047 people are learning the system