zoukankan      html  css  js  c++  java
  • 创建

    1.用可见的方式:数据库优先和模型优先;

    2.根据代码创建数据库和上下文:

    (1)建数据模型(几张表就建几个模型)

    public class M
    {
    public string name { get; set; }
    public int age { get; set; }
    [Key] //指定主键。需要添加引用using System.ComponentModel.DataAnnotations;
    public int id { get; set; }
    public virtual M xff { get; set; }
    }
    (2)连接数据库的字符串

    <connectionStrings>
    <!--Data Source=(local)。。表示连接的数据库服务是本地;Initial Catalog=A。。连接的数据库是A;Integrated Security=True。。Windows验证连接-->
    <!--connectionString="Data Source=localhost;Initial Catalog=数据库名称;User ID=用户名;Password=密码"-->
    <!--name里面是你起的名字,是什么都无所谓,但在cs代码中调用要对应这个name-->
    <add connectionString="Data Source=(local);Initial Catalog=B;Integrated Security=True" name="B_connection" providerName="System.Data.SqlClient" />

    </connectionStrings>

    (3)创建上下文

    public class CodeFirst:DbContext
    {
      public CodeFirst()
      : base("name=B_connection") //连接字符串的属性name=AEntities
      { }
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
        //throw new UnintentionalCodeFirstException();
      }
      public virtual DbSet<M> M { get; set; }//M是自己创建是数据模型,会根据数据模型创建表,几个模型几张表
    }

    (4)创建

    public string CreateTabel()
    {
    CodeFirst codefirst = new CodeFirst(); //声明上下文
    codefirst.Database.CreateIfNotExists(); //创建数据库
    return "创建成功";
    }

    最后会在数据库中看到连接字符串中定义的一个数据库,和根据数据模型创建的表。现在就可以通过上下文来进行操作类类。

  • 相关阅读:
    添加外部文件夹代码文件到项目中使用
    在.NET Core console application中使用User Secrets(用户机密)
    RBAC用户特别授权的思考
    Service Fabric部署笔记
    ubuntu12.04 rvm 搭建 Ruby on Rails
    thinkphp 查询当天 ,本周,本月,本季度,本年度,全部, 数据方法
    php 计算该用户IP在网页停留的时间
    ubuntu下安装sublime text2
    快速找到php方法-------php 反射。。
    QQ快速登录
  • 原文地址:https://www.cnblogs.com/it-xcn/p/5698521.html
Copyright © 2011-2022 走看看