zoukankan      html  css  js  c++  java
  • .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

    技术分享图片

    技术分享图片

    数据库生成成

    注册容器

    构造函数注入

    数据访问层

  • 相关阅读:
    ie6 浏览器的bug
    hack (浏览器兼容css hack)
    jquery操作select下拉框的多种方法(选中,取值,赋值等)
    php 环境搭配 脚本模式(1)
    JQuery限制文本框只能输入数字和小数点的方法
    使用jOrgChart插件, 异步加载生成组织架构图
    JavaScript 输出
    Java开发环境的搭建以及使用eclipse从头一步步创建java项目
    git cherry-pick
    <a>标签的href、onclick属性
  • 原文地址:https://www.cnblogs.com/KyrieCC/p/9985442.html
Copyright © 2011-2022 走看看