.NET

.NET Core Entity Framework Part

2018-09-30  本文已影响0人  Charles2018

Entity Framework 是一个方便的数据库基架,比方说你在项目某个文件夹下创建了一个如下所示的Person类

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Job { get; set; }
        public int Age { get; set; }
    }

然后动再做小小的配置, 框架就可以自动帮你创建一个数据库,并且自动添加一张为Person的表,各字段与Person属性一一对应。此框架支持MySql、SqlServer、oracle等。。。

此篇讲述简单的EF内存模拟数据库测试,第二篇讲述使用真实的数据库。

创建项目

安装 Entity Framework

点击菜单栏“工具”>“NuGet 包管理器”>“包管理器控制台”
运行 Install-Package Microsoft.EntityFrameworkCore.InMemory
在本教程的后面部分,你会使用某些 Entity Framework Tools 维护数据库。 因此,请同时安装该工具包。
运行 Install-Package Microsoft.EntityFrameworkCore.Tools

创建模型

现在是时候定义构成模型的上下文和实体类了。
在项目中创建一个Database文件夹,然后在Database文件夹,在Database文件夹下创建一个Table文件夹并添加Person.cs替换代码如下所示:

namespace ConsoleApp.NewDb.Database.Table
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Job { get; set; }
        public int Age { get; set; }
    }
}

创建数据库上下文

在Database文件夹下创建DBContext.cs文件如下所示;

using ConsoleApp.NewDb.Database.Table;
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp.NewDb.Database
{
    class DBContext : DbContext
    {
        public DbSet<Person> Person { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseInMemoryDatabase("PersonList");
        }
    }
}

其中optionsBuilder.UseInMemoryDatabase("PersonList");意味着在内存中模拟一个数据库。在下一篇博客我们再讲述使用真实的数据库。

读写数据库数据

现在可以使用模型执行数据访问。
打开 Program.cs
将此文件的内容替换为以下代码

using ConsoleApp.NewDb.Database;
using ConsoleApp.NewDb.Database.Table;
using System;

namespace ConsoleApp.NewDb
{
    class Program
    {
        static void Main(string[] args)
        {
            // Which mean, Get context of the database.
            DBContext context = new DBContext();
            
            // Initialize table records of the database.
            context.Person.AddRange(
                new Person { Name = "猪猪", Job = "程序员", Age = 20 },
                new Person { Name = "妞妞", Job = "程序媛", Age = 22 },
                new Person { Name = "板凳", Job = "程序猿", Age = 44 }
                );

            // Update the database records.
            context.SaveChanges();

            // Remove at 3 of the id.
            Person oldPerson = context.Person.Find(3);
            context.Person.Remove(oldPerson);
            context.SaveChanges();

            // Insert a new data of the Person
            context.Person.Add(new Person { Name = "蛋蛋", Job = "项目经理", Age = 35 });
            context.SaveChanges();

            foreach (Person p in context.Person)
            {
                Console.WriteLine();
                Console.WriteLine($"Name:{p.Name}\nJob:{p.Job}\nAge:{p.Age}");
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}
  1. 其中DBContext context = ..意思是得到一个数据库上下文或者说是把柄。

  2. context.Person.AddRange(...)意味着初始化一些数据。以便于后面进行读写操作。

  3. 因为我们第2点做了初始化操作,所以我们必须要调用一下context.SaveChanges()更新一下数据库里的数据。因为框架先把我们做新增的数据放到了储存区。直到你调用了context.SaveChanges()才会从储存区添加到数据库。

  4. Person oldPerson = context.Person.Find(3)意思是从context.Person集合 或(数据库)中搜索id为3的Person。此id就是你创建的Person.cs类里面的那个id属性。找到之后返回给oldPerson对象,再调用context.Person.Remove(oldPerson)从数据库中移除此Person。调用context.SaveChanges()保存更改。

5.context.Person.Add(..)向储存区插入一条新的Person然后调用contetx.SaveChanges()更新数据。

6.foreach(var ... in ...) 遍历context.Person集合数据,结果如下:

image.png
上一篇 下一篇

猜你喜欢

热点阅读