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 "创建成功";
    }

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

  • 相关阅读:
    HDU.5765.Bonds(DP 高维前缀和)
    SPOJ.TLE
    LOJ.2585.[APIO2018]新家(二分 线段树 堆)
    BZOJ.2679.Balanced Cow Subsets(meet in the middle)
    BZOJ.3293.[CQOI2011]分金币(思路)
    BZOJ.4558.[JLOI2016]方(计数 容斥)
    BZOJ.3631.[JLOI2014]松鼠的新家(树上差分)
    BZOJ.1568.[JSOI2008]Blue Mary开公司(李超线段树)
    BZOJ.1071.[SCOI2007]组队(思路)
    BZOJ.4910.[SDOI2017]苹果树(树形依赖背包 DP 单调队列)
  • 原文地址:https://www.cnblogs.com/it-xcn/p/5698521.html
Copyright © 2011-2022 走看看