Entity Framework learning notes 1 Books

Introduction to Entity Framework

The first version of Entity FrameWork 1 is not ready for use in. net3.5. One product is LINQ to SQL, which provides similar functions and can be used in. net3.5. In a broad sense, LINQ to SQL and Entity FrameWork provide similar functions. However, LINQ to SQL is simpler to use, but only for accessing SQL Server. Entity FrameWork is provider based and can access several different relational databases. It contains more functions, such as many to many mapping, no need to map the object, can be n to n mapping. One disadvantage of Entity FrameWork is that it requires the model type to derive from the enityobject base class. Use an edmx file containing xml to map objects to relationships.

Entity FrameWork 4 can be used in. net4 for medium and large improvements, and many ideas come from linqtosql. Version 2 and 3 were skipped due to large changes. In this version, delayed loading is added to obtain the relationship when accessing the property. After designing the model, you can use sql data definition language to create the database. The two models that use Entity FrameWork are databasefirst or ModelFirst. An important feature added is to support all obstacles of Plain Old derived from the base class EntityObject.

NuGet package of Entity FrameWork 5 supports. net4.5 and. Net 4. However, many functions of Entity FrameWork 5 can be used for net 4.5. Entity FrameWork is still based on the type installed on the system and. net4.5. In this version, new performance improvements are added to support new SqlServer functions, such as control data type.

Entity FrameWork 6 solves some functions of Entity FrameWork 5. Part of the reason is that part of the framework is installed on the system and part of it is obtained through nuget extension. Now the complete code of Entity FrameWork is moved to nuget package. Use a new namespace to avoid conflicts. To migrate an application to a new version, you must change the namespace

This chapter introduces the latest version of Entity FrameWork. The version of Entity FrameWork Core 1.0 has been completely rewritten to remove the old behavior. This version does not support xml file mapping with CSDL, SSDL, and MSL. Only Entity FrameWork 4 for Code First is supported. 1 added model.

Entity FrameWork Core 1.0 does not support all the functions of Entity FrameWork 6 temporarily, but the new version of Entity FrameWork Core will provide more features over time. Just pay attention to the version of Entity FrameWork Core. Using asp on non windows platform. The Entity FrameWork and general windows platform are used in nent core 1.0, and the Entity FrameWork Core 1.0 is required for the usage fee relationship data storage.

 

First example of Entity Framework

The first example uses a Book type that maps to the books table in the SQL Server database. Write records to the database and read, update, and delete them.

In the first example, create the database first, and use SQL SERVER 2008 R2 here. The sample database has only one table Books.

In order to create the books table, you can create a new books database and use T-SQL code to create the database in the database

CREATE TABLE [ado].[Books]
{
    [BookID] INT NOT NULL PRIMARY KEY IDENTITY,
    [Title] NVARCHAR(50) NOT NULL,
    [Publisher] NVARCHAR(25) NOT NULL
}

Create model

The BookSample sample sample application that accesses the Books database is a console program (package). This example uses the following dependencies and namespaces

Install from NuGet

The Book class is a simple entity type that defines three properties. The BookID property is mapped to the primary key of the Table, the Title property to the Title column, and the Publisher property to the Publisher column. To map types to Books tables, the Table attribute applies to types

using System;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using static System.Console;

namespace booksCore
{
    [Table("Books")]
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Publisher { get; set; }
    }
}

 

Create context

By creating the BooksContext class, the relationship between the Book table and the database is realized. This class derives from the base class DbContext. BooksContext class, which defines the Books attribute of type dbset < Book >. This type runs the create query, adds the Book instance, and stores it in the database. To define a connection string, override the OnConfiguring method of DbContext. Here, the UseSqlServer extension method maps the context to the Sql server database

 

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;

namespace booksCore
{
    public class BooksContext : DbContext
    {
        private const string ConnectionString = "";
        public DbSet<Book> Books { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(ConnectionString);

        }
    }
}

 

Write to database

Create a database with Books tables; define models and context classes, and now you can populate the tables with data. Create the AddBookAsync method to Add the Book object to the database. First, instantiate the BooksContext object. Use the using statement to ensure that the database connection is closed. After adding the object to the context using the Add method, call savechangesasyn to write the entity to the database

        private async Task AddBookAsync(string title, string publisher)
        {
            using (var context = new BooksContext())
            {
                var book = new Book { Title = title, Publisher = publisher };
                context.Add(book);
                int records = await context.SaveChangesAsync();

                WriteLine($"{records} record added");
            }
            WriteLine();
        }

 

To add a set of books, you can use the AddRange method

        private async Task AddBooksAsync()
        {
            using (var context = new BooksContext())
            {
                var b1 = new Book { Title = "Professional C# 5 and .NET 4.5.1", Publisher = "Wrox Press" };
                var b2 = new Book { Title = "Professional C# 2012 and .NET 4.5", Publisher = "Wrox Press" };
                var b3 = new Book { Title = "JavaScript for Kids", Publisher = "Wrox Press" };
                var b4 = new Book { Title = "Web Design with HTML and CSS", Publisher = "For Dummies" };
                var b5 = new Book { Title = "Conflict Handling", Publisher = "Test" };
                context.AddRange(b1, b2, b3, b4, b5);
                int records = await context.SaveChangesAsync();

                WriteLine($"{records} records added");
            }
            WriteLine();
        }

Read database

In order to read data in C code, you only need to call BooksContext to access the Books property. Accessing this property creates an SQL statement that retrieves all Books from the database

        private void ReadBooks()
        {
            using (var context = new BooksContext())
            {
                var books = context.Books;
                foreach (var b in books)
                {
                    WriteLine($"{b.Title} {b.Publisher}");
                }
            }
            WriteLine();
        }

The Entity Framework provides a LINQ provider. Use it to create LINQ queries to access the database. It can also be used as follows:

        private void QueryBooks()
        {
            using (var context = new BooksContext())
            {
                var wroxBooks = context.Books.Where(b => b.Publisher == "Wrox Press");

                // comment the previous line and uncomment the next lines to try the LINQ query syntax
                //var wroxBooks = from b in context.Books
                //                where b.Publisher == "Wrox Press"
                //                select b;
                foreach (var b in wroxBooks)
                {
                    WriteLine($"{b.Title} {b.Publisher}");
                }
            }
            WriteLine();
        }

Update record

Updating records is easy: modify the context loaded object and call saveChangesAsync

        private async Task UpdateBookAsync()
        {
            using (var context = new BooksContext())
            {
                int records = 0;
                var book = context.Books.Where(b => b.Title == "Professional C# 6").FirstOrDefault();
                if (book != null)
                {
                    book.Title = "Professional C# 6 and .NET Core 5";
                    records = await context.SaveChangesAsync();
                }

                WriteLine($"{records} record updated");
            }
            WriteLine();
        }

Delete record

Finally, clean up the database and delete all records. To do this, you can retrieve all records and call the Remove or Removerang methods to set the state of the object in the context to Remove. Now call the DeleteBooksAsync method, delete the records from the database, and call the sql delete statement for each object

        private async Task DeleteBooksAsync()
        {
            using (var context = new BooksContext())
            {
                var books = context.Books;
                context.Books.RemoveRange(books);
                int records = await context.SaveChangesAsync();
                WriteLine($"{records} records deleted");
            }
            WriteLine();
        }

 

21 original articles published, praised 0, and 718 visitors
Private letter follow

Tags: Database SQL xml Windows

Posted on Thu, 13 Feb 2020 22:05:45 -0800 by tasairis