The existing database uses Entity Framework 6.0 Code First

1. Create a database

Create database BloggingDatabase in SQL Server Management Studio

Create a Blogs table and a Posts table in the database BloggingDatabase.

CREATE TABLE [dbo].[Blogs] (
[BlogId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NULL,
[Url] NVARCHAR (250) NULL,
CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY CLUSTERED ([BlogId] ASC)
);

CREATE TABLE [dbo].[Posts] (
[PostId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (50) NULL,
[Content] NTEXT NULL,
[BlogId] INT NOT NULL,
CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED ([PostId] ASC),
CONSTRAINT [FK_dbo.Posts_dbo.Blogs_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [dbo].[Blogs] ([BlogId]) ON
DELETE CASCADE
);

INSERT INTO [dbo].[Blogs] ([Name],[Url])
VALUES ('CSDN upload resource review is slow', 'https://csdn.s2.udesk.cn/im_client/')
INSERT INTO [dbo].[Blogs] ([Name],[Url])
VALUES ('What is the URL of CSDN', 'https://www.csdn.net/')

2. Create a new entity data model

Use Visual Studio’s AOD.NET Entity Framework tools to generate some code to map to the database.

Select the Code First schema from the database.

Click the New Connection button to create a database connection, fill in the server address, user name and password, then select the BloggingDatabase database, and then click the Next button.

Click the arrow button, select the Blogs and Posts tables, click the Finish button, and the connection string of the database whose node name is Bloggingcontext will be automatically added to the App.config file.

New additions to the App.config file.

 <connectionStrings>
    <add name="Bloggingcontext" connectionString="data source=server address;initial catalog=BloggingDatabase;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
  • At the same time, the Bloggingcontext class that inherits DbContext is added, which contains two attributes of DbSet type with virtual decoration, which correspond to the Blogs and Posts tables of the database BloggingDatabase respectively.

  • public Bloggingcontext() : base(“name=Bloggingcontext”) Read the node name in App.config as the Bloggingcontext connection database string through the database connection convention.

Derived context Bloggingcontext class

 public partial class Bloggingcontext : DbContext
    {
        public Bloggingcontext()
            : base("name=Bloggingcontext")
        {
        }

        public virtual DbSet<Blogs> Blogs { get; set; }
        public virtual DbSet<Posts> Posts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }

Template classes Blogs and Posts

Additionally, the Blogs and Posts classes are added to the project, and the BlogId field of the Blogs class is added with a “[Key]” data annotation to specify the primary key of the BloggingDatabase table Blogs. The ‘[StringLength(250)]’ of the Name property specifies the maximum length supported by the table field Name. The data annotation for the Posts navigation property is an auto-generated identifier.

Blogs class

 public partial class Blogs
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Blogs()
        {
            Posts = new HashSet<Posts>();
        }

        [Key]
        public int BlogId { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        [StringLength(250)]
        public string Url { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Posts> Posts { get; set; }
    }

Posts class

 public partial class Posts
    {
        [Key]
        public int PostId { get; set; }

        [StringLength(50)]
        public string Title { get; set; }

        [Column(TypeName = "ntext")]
        public string Content { get; set; }

        public int BlogId { get; set; }

        public virtual Blogs Blogs { get; set; }
    }

3. Read and write data

Implement adding a record to the Blog table in the Main method of the Program.cs file, and use LINQ query to find all records from the Blog table, and finally traverse and output these records.

 internal class Program
    {
        static void Main(string[] args)
        {
            using (var db = new Bloggingcontext())
            {
                // Create and save a Blog instance
                Console.Write("Enter the blog name: ");
                var name = Console. ReadLine();
                var blog = new Blogs { Name = name };
                db.Blogs.Add(blog);
                db. SaveChanges();

                // Traverse all records of Blog
                var query = from b in db.Blogs
                            order by b.Name
                            select b;
                foreach (var item in query)
                {
                    Console. WriteLine(item. Name);
                }

                Console. ReadKey();
            }
        }
    }

4. Migration

The migration feature incrementally updates the database schema to keep it in sync with the application’s data model while preserving existing data in the database.

For detailed steps, please refer to the migration chapter of “Entity Framework 6.0 Code First”.