.netcore初体验

Asp.net Core 2.1使用 EF Core 简单增删改查操作数据库 大概步骤如下5步:

1、创建项目(Asp.net Core 2.1项目)

2、项目使用EF Core

3、建立实体

4、生成迁移文件(生成数据库)

5、使用VS工具生成视图、控制器代码

 示例代码下载  https://github.com/ZhMartincheng/NetCoreDemo.git

1、创建项目(Asp.net Core 2.1项目)

 技术分享图片

选择.net core 版本2.1

技术分享图片

 

 基础项目创建成功技术分享图片

 

 

2、项目使用EF Core

2.1、通过nuget 安装Microsoft.EntityFrameworkCore.SqlServer

项目右键管理nuget包

技术分享图片

技术分享图片

 安装成功

技术分享图片

 

3、建立实体

 

 

班级实体(一个班级多个学生)

 public class ClassEntiy
    {

        public int ID { get; set; }

        public string ClassName { get; set; }


        public virtual ICollection<Student> Students { get; set; }

    }

  技术分享图片

 

 

 

4、生成迁移文件(生成数据库)

 配置链接字符串 "ConnectionStrings": {"SqlServer": "Data Source=.;Initial Catalog=TestDb;User Id=sa;Password=123;"}

技术分享图片

创建 上下文对象 DbContext 

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCoreDemo.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }
        public DbSet<Student> Student { get; set; }
        public DbSet<ClassEntiy> ClassEntitys { get; set; }
    }
}

 技术分享图片

 

代码配置数据库链接串

var connection = Configuration.GetConnectionString("SqlServer");
services.AddDbContext<NetCoreDemo.Models.ApplicationDbContext>(options =>
options.UseSqlServer(connection, b => b.MigrationsAssembly("NetCoreDemo")));

  

 

技术分享图片

 编译成功后执行生成迁移文件命令add-Migration Init

技术分享图片

通过迁移文件生成数据库Update-Database

技术分享图片

技术分享图片

数据库生成成

注册容器

构造函数注入

数据访问层

 

转载于:https://www.cnblogs.com/KyrieCC/p/9985442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值