• Create demo project with EntityFramework Core


    Create demo project with EntityFramework Core

    Quick link overview[快速访问连接地址]:

    Dependencies【依赖说明】

    在这里插入图片描述
    The project code refer office document, you can see : https://learn.microsoft.com/zh-cn/ef/【项目可以参考官方文档,参考地址】

    Code First【Code First】

    Product

    namespace EFCoreConsoleApp.Models
    {
        public class Product
        {
            
            public int Id { set; get; }
    
            public string Name { set; get; } = null!;
    
            [Column(TypeName="decimal(6,2)")]
            public decimal Price { get; set; }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    OrderDetail

    namespace EFCoreConsoleApp.Models
    {
        public class OrderDetail
        {
            public int Id { get; set; }
            public int Quantity { get; set; }
            public int ProductId { get; set; }
            public int OrderId { get; set; }
    
            public Order Order { get; set; } = null!;
            public Product Product { get; set; } = null!;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Order

    namespace EFCoreConsoleApp.Models
    {
        public class Order
        {
            public int Id { get; set; }
            public DateTime OrderPlaced { get; set; }
            public DateTime? OrderFulfilled { get; set; }
            public int CustomerId { get; set; }
    
            public Customer Customer { get; set; } = null!;
            public ICollection OrderDetails { get; set; } = null!;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Customer

    namespace EFCoreConsoleApp.Models
    {
        public class Customer
        {
            public int Id { get; set; }
            public string FirstName { get; set; } = null!;
            public string LastName { get; set; } = null!;
            public string? Address { get; set; }
            public string? Phone { get; set; }
            public string? Email { get; set; }
            public int? sex { get; set; }
    
            public ICollection Orders { get; set; } = null!;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Create DbContext

    MyLocalContext

    namespace EFCoreConsoleApp.Data
    {
        public class MyLocalContext : DbContext
        {
    
            public DbSet Customers { get; set; } = null!;
            public DbSet Orders { get; set; } = null!;
            public DbSet Products { get; set; } = null!;
            public DbSet OrderDetails { get; set; } = null!;
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                // Get the connection string pattern from : https://learn.microsoft.com/en-us/ef/core/
                optionsBuilder.UseSqlServer("Server=localhost;Database=EFCore;User Id=sa;Password=xxxx123");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Migrations[迁移工具]

    Install the tool【安装方式】

    The EF Core tools help with design-time development tasks. They are primarily used to manage Migrations and to scaffold a DbContext and entity types by reverse enginerring the schema of a database.

    Install the Package manager Console tools by runing the following command in Package Manager Console.【执行安装命令】

    Install-Package Microsoft.EntityFrameworkCore.Tools
    
    • 1

    Update the tools by running the following command in Package Manager Console.

    Update-Package Microsoft.EntityFrameworkCore.Tools
    
    • 1

    Verify taht the tools are installed by running the following command:

    Get-help about_EntityFrameworkCore
    
    • 1

    OR

    dotnet ef can be installed as either a global ot local tools. I recommand you to install it as global tools, because most developers do like that.【Mac 命令行执行方式】

    Using the following command to install the tools:

    dotnet tool install --global dotnet-ef
    
    • 1

    Using the following command to update the tools:

    dotnet tool update --global dotnet-ef
    
    • 1

    Before you can use the tools on a special project, you will need to add the Microsoft.EntityFrameCore.Design package to it:

    dotnet add package Microsoft.EntityFrameworkCore.Design
    
    • 1

    Verify installation:【验证安装效果】
    在这里插入图片描述

    Add migration【执行迁移工具】

    After finished the prepartion, you can generate table by running the following command in order:

    dotnet ef migrations add InitialCreate
    dotnet ef database update
    
    • 1
    • 2

    You can also refer Migration Commands to implement the same result by running command in your VS IDE.

    Add-Migration InitialCreate
    Update-Database
    
    • 1
    • 2

    Verify the local database tables:【得到创建的表结果】
    在这里插入图片描述

    Test operations【测试代码】

    Here are some demo code to insert or update some data to your database, you can try that and help you release how to do CRUD with EFCore:

    
    using MyLocalContext context = new MyLocalContext();
    
    # region Add Products
    
    // Create a new product
    Product veggiSpecial = new Product()
    {
        Name = "Veggie Special Pizza",
        Price = 9.9M
    };
    // Save product
    context.Products.Add(veggiSpecial);
    
    Product deluxeMeat = new Product()
    {
        Name = "Deluxe Meat Pizza",
        Price = 12.99M
    };
    context.Products.Add(deluxeMeat);
    
    context.SaveChanges();
    
    #endregion
    
    #region display products
    var products = context.Products
        .Where(p => p.Price > 10.0M)
        .OrderBy(p => p.Price);
    
    Console.WriteLine("Use function method way:");
    foreach (Product p in products)
    {
        Console.WriteLine($"Id:    {p.Id}");
        Console.WriteLine($"Name:  {p.Name}");
        Console.WriteLine($"Price: {p.Price}");
        Console.WriteLine(new string('-', 20));
    }
    #endregion
    
    #region linqProduct
    
    var productsLinq = from product in context.Products
                   where product.Price >= 10.0M
                   orderby product.Price descending
                   select product;
    
    Console.WriteLine("Use Linq way:");
    foreach (Product p in productsLinq)
    {
        Console.WriteLine($"Id:    {p.Id}");
        Console.WriteLine($"Name:  {p.Name}");
        Console.WriteLine($"Price: {p.Price}");
        Console.WriteLine(new string('-', 20));
    }
    #endregion
    
    #region update product
    var veggiSpecialUpdate = context.Products
        .Where(p => p.Name == "Veggie Special Pizza")
        .FirstOrDefault();
    
    if (veggiSpecialUpdate is Product)
    {
        veggiSpecialUpdate.Price = 11.11M;
    }
    
    context.SaveChanges();
    #endregion
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    Result as sinpshot:【展示效果】
    在这里插入图片描述


    You can get the first EFCore project by follow the blob step by step. We can have a discussion in private If you meet any problems when create your demo code.
    Hope it is helpul for you !【希望有所帮助】

  • 相关阅读:
    006:连续跌三天,第四天上涨的概率--用python统计
    hcie培训价格多少钱?
    单身福利专场, Python采集某相亲网站美女数据
    CRM客户管理系统究竟是什么?如何实施?
    Java 网络编程、e-mail、多线程编程
    24.面向对象六大原则
    10、正则表达式 (笔试题、语法规则、正则对象方法、正则实例属性、支持正则表达式的String对象的方法、贪婪匹配与非贪婪匹配)
    protel9s【硬件课程设计】
    下一代实时数据库:Apache Doris 【一】简介
    Jira系统基本介绍
  • 原文地址:https://blog.csdn.net/qq_32112175/article/details/127717537