zoukankan      html  css  js  c++  java
  • Entity Framework,EF 手动DB FIRST,不使用设计器

    环境:

    VS2019

    SQL SERVER 2012

    一、在数据库(db1)创建表结构

    “db1”是数据库名,“Table1”是表名。

    USE [db1]
    GO
    
    /****** Object:  Table [dbo].[Table1]    Script Date: 2020/12/30 10:14:54 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE TABLE [dbo].[Table1](
        [aa] [bigint] IDENTITY(1,1) NOT NULL,
        [bb] [nvarchar](50) NULL,
        [cc] [nvarchar](50) NULL,
     CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED 
    (
        [aa] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO

    二、在VS里新建一个WINFORM项目

    基于.NET FRAMEWORK 4.5.2

    1.使用nuget下载“EntityFramework”,此时最新版本是6.4.4。

    下载成功后,可以观察到app.config已被自动修改,在原有基础上新增了“configSections”、“entityFramework”两个配置节。原始只有“startup”。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
            <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
            <section name="entityFramework"
              type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
              requirePermission="false"/>
        </configSections>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
        </startup>
    
      <connectionStrings>
        <add name="Db1Context" connectionString="Data Source=localhost;Initial Catalog=db1;MultipleActiveResultSets=True;User ID=sa;Password=som;Pooling=true;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
      
        <entityFramework>
            <providers>
                <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
            </providers>
        </entityFramework>
    </configuration>

    2.新建“Table1”实体类,并设置主键和自增长列,与表结构保持一致

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace WindowsFormsEFdbFirst.DbModel
    {
        public class Table1
        {
            [Key] //主键 
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //设置自增
            public long aa { get; set; }
    
            public string bb { get; set; }
    
            public string cc { get; set; }
    
        }
    }

    3.新建“Db1DbContext”

    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using WindowsFormsEFdbFirst.DbModel;
    
    namespace WindowsFormsEFdbFirst.DbContext2
    {
        public class Db1DbContext : DbContext
        {
            public Db1DbContext()
                : base("name=Db1Context")
            {
            }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //移除复数表名
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                
                base.OnModelCreating(modelBuilder);
            }
    
            public virtual DbSet<Table1> Table1s { get; set; }
        }
    }

    4.界面上添加一个BUTTON,双击添加点击事件。

    private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    using (Db1DbContext db1 = new Db1DbContext())
                    {
                        Table1 t1 = new Table1();
                        t1.bb = "bb" + DateTime.Now.ToString();
                        t1.cc = "c" + DateTime.Now.ToString();
    
                        db1.Table1s.Add(t1);
                        db1.SaveChanges();
                    }
                    MessageBox.Show("完成");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

    插入一条记录做演示。

  • 相关阅读:
    Python学习心得第二周-作业
    Python学习心得第二周-02 字符串、列表、元组、字典
    Python学习心得第二周-01 数字类型
    eclipse 性能调优之内存分配
    Spring 面试
    技巧 linux 如何显示一个文件的某几行(中间几行)
    命令 scp
    机器学习遇到的好的资料
    maven 使用记录
    “冷启动”问题浅析
  • 原文地址:https://www.cnblogs.com/runliuv/p/14210108.html
Copyright © 2011-2022 走看看