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; }
    }
}

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!;
    }
}

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<OrderDetail> OrderDetails { get; set; } = null!;
    }
}

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<Order> Orders { get; set; } = null!;
    }
}

Create DbContext

MyLocalContext

namespace EFCoreConsoleApp.Data
{
    public class MyLocalContext : DbContext
    {

        public DbSet<Customer> Customers { get; set; } = null!;
        public DbSet<Order> Orders { get; set; } = null!;
        public DbSet<Product> Products { get; set; } = null!;
        public DbSet<OrderDetail> 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");
        }
    }
}

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

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

Update-Package Microsoft.EntityFrameworkCore.Tools

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

Get-help about_EntityFrameworkCore

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

Using the following command to update the tools:

dotnet tool update --global dotnet-ef

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

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

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

Add-Migration InitialCreate
Update-Database

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

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 !【希望有所帮助】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值