zoukankan      html  css  js  c++  java
  • EntityFramework Core笔记:入门(1)

    1. 安装运行环境

      EntityFramework Core运行环境,安装NuGget包:

    //Sql Server Database Provider
    PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
    //提供Add-Migration,Update-Database等Powershell命令
    PM> Install-Package Microsoft.EntityFrameworkCore.Tools 

    2. 控制台程序

    2.1 基础代码

      实体类:Role.cs

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Libing.App.Models.Entities
    {
        public class Role
        {
            public int RoleID { get; set; }
    
            public string RoleName { get; set; }
        }
    }
    Role.cs

      DbContext.cs

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using Microsoft.EntityFrameworkCore;
    
    using Libing.App.Models.Entities;namespace Libing.App.Models
    {
        public class LibingContext : DbContext
        {
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                // 数据库连接
                optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=Libing;Integrated Security=True;");
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
            }
    
            public DbSet<Role> Roles { get; set; }
        }
    }

    2.2 生成表结构

    PM> Add-Migration InitialCreate
    PM> Update-Database

    2.3 运行代码

    using System;
    
    using Libing.App.Models;
    using Libing.App.Models.Entities;
    
    namespace Libing.App
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var context = new LibingContext())
                {
                    var role = new Role
                    {
                        RoleName = "管理员"
                    };
    
                    context.Roles.Add(role);
    
                    context.SaveChanges();
                }
            }
        }
    }

      执行的SQL语句:

    exec sp_executesql N'SET NOCOUNT ON;
    INSERT INTO [dbo].[Role] ([RoleName])
    VALUES (@p0);
    SELECT [RoleID]
    FROM [dbo].[Role]
    WHERE @@ROWCOUNT = 1 AND [RoleID] = scope_identity();
    
    ',N'@p0 nvarchar(100)',@p0=N'管理员'
  • 相关阅读:
    【设计总结】粤省事
    【设计】如何准备自己的作品集
    【设计】体系化设计思路
    【ML】京东人工智能设计神器「羚珑」
    【sqlalchemy】
    php代码审计基础笔记
    让windows瞬间cpu满载到100的批处理
    获取当前 Windows 的安装序列号
    CVE-2013-3908 Internet Explorer打印预览功能可导致信息泄露
    U-Mail邮件服务系统任意文件上传+执行漏洞(runtime缺陷与验证绕过)
  • 原文地址:https://www.cnblogs.com/libingql/p/9096267.html
Copyright © 2011-2022 走看看