Entity Framework Core 从 Model 到 Database

  在曾经初学 C# 之时,为了做数据持久化,还是先在数据库中创建好数据库及数据表对象,在代码中还需要手动继续写一遍数据模型,这一系列的操作是多么的麻烦啊。其实,大可不必这样,这里就简单说说从模型到数据库的操作。

创建项目

  新增一个 EFCore 的项目,项目名称为 EFCoreDemo ,引入如下 NuGet 包。

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

  在项目中创建两个文件夹: ModelsDataBase

创建模型

  在 Models 文件夹中添加两个类文件: T_blogList.csT_blogContent.cs
  T_blogList.cs 中的代码如下:

using System;
using System.ComponentModel.DataAnnotations;

namespace EFCoreDemo.Models
{
    class T_blogList
    {
        [Key]
        public Guid Id { get; set; }
        [Required]
        [MaxLength(100)]
        public string Title { get; set; }
        [Required]
        public DateTime creationDateTime { get; set; }
        [Required]
        [MaxLength(100)]
        public string author { get; set; }
    }
}

  T_blogContent.cs 中的代码如下:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFCoreDemo.Models
{
    class T_blogContent
    {
        [Key]
        public Guid Id { get; set; }
        [Required]
        [MaxLength]
        public string Content { get; set; }
        [ForeignKey("T_blogListId")]
        public Guid blogListId { get; set; }
    }
}

创建 DbContext

  在 Database 文件夹中创建类文件 EFCoreDbContext.cs ,键入如下代码:

using EFCoreDemo.Models;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.DataBase
{
    class EFCoreDbContext : DbContext
    {
        public DbSet<T_blogList> T_blogLists { get; set; }
        public DbSet<T_blogContent> T_BlogContents { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseSqlServer(@"{数据库连接字符串}");
    }
}

模型映射到数据库

  点击 Visual Studio 2019 菜单栏:【视图】→【其他窗口】→【程序包管理控制台】。
在这里插入图片描述
  在程序包管理控制台依次执行以下命令:

PM> add-migration InitialCreate1
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> update-database
Build started...
Build succeeded.
Applying migration '20210710153029_InitialCreate1'.
Done.
PM> 

  这两条命令可以将模型生成数据库及数据表创建脚本,并根据提供的数据库连接字符串将数据库脚本执行到数据库中,最终我们可以在数据库中看到我们通过以上这些步骤所创建好的数据库:
在这里插入图片描述

使用演示

  在 Program.cs 类文件中键入如下代码:

using EFCoreDemo.DataBase;
using EFCoreDemo.Models;
using System;
using System.Linq;

namespace EFCoreDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new EFCoreDbContext())
            {
                // 执行数据库插入操作
                Console.WriteLine("向数据库插入一条数据:");
                // 这里可以不用给 T_blogContent 实体的ID字段赋值,EFCore会自动生成一个 GUID
                db.Add(new T_blogContent { Content = "这是一篇博客的演示内容,这条数据将插入到数据库中", blogListId = Guid.NewGuid() });
                // 执行保存操作
                db.SaveChanges();

                // 执行读取数据库数据操作  
                Console.WriteLine("从数据库中读取数据:");
                var blogContentList = db.T_BlogContents.OrderBy(b => b.Id).First();
                Console.WriteLine("{0}\t{1}\t{2}", blogContentList.Id, blogContentList.Content, blogContentList.blogListId);

                // 更新数据库中的数据
                Console.WriteLine("更新数据表中的数据:");
                blogContentList.Content = "这条数据已经被修改了!";
                db.SaveChanges();
                var blogContentList2 = db.T_BlogContents.OrderBy(b => b.Id).First();
                Console.WriteLine("{0}\t{1}\t{2}", blogContentList2.Id, blogContentList2.Content, blogContentList2.blogListId);

                // 删除数据库表中的数据   
                Console.WriteLine("删除数据库表中的数据");
                db.Remove(blogContentList2);
                db.SaveChanges();
            }
            Console.WriteLine("数据库操作结束,按任意键退出:");
            Console.ReadKey();
        }
    }
}

演示源码

  以下为代码仓库的源码连接:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
System.InvalidOperationException: The LINQ expression 'DbSet<z_tjdj_yydj>() .Where(z => z.YYBH.Substring( startIndex: 0, length: z.YYBH.Length - 6) == __Substring_0) .Max(z => int.Parse(z.YYBH.Substring( startIndex: 10, length: 5)))' could not be translated. Additional information: Translation of method 'int.Parse' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& ) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query) at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.Max[TSource,TResult](IQueryable`1 source, Expression`1 selector) at VOL.TJYY.Services.z_tjdj_yydjService.<>c__DisplayClass10_0.<Import1>b__0(List`1 list) at VOL.Core.BaseProvider.ServiceBase`2.Import(List`1 files) in D:\work\TJYYHT_VOL\Net6版本\VOL.Core\BaseProvider\ServiceBase.cs:line 459 at VOL.TJYY.Services.z_tjdj_yydjService.Import(List`1 files) at VOL.TJYY.Services.z_tjdj_yydjService.Import1(List`1 fileInput, Dictionary`2 data) at VOL.TJYY.Controllers.z_tjdj_yydjController.Import1(List`1 fileInput, Dictionary`2 data) at lambda_method901(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
最新发布
06-10

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值