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

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

  • 相关阅读:
    我谈编程语言竞争
    从基础学起----xuld版高手成长手记[1]
    自己动手开发语言.笔记@2014-1-13
    删除 QQ 最新版右键菜单 通过QQ发送文件到手机
    客观评价C#的优点和缺点
    一个会做你就是高手的问题
    计划开发的语言及一些细节求吐槽
    面向接口设计思想
    计划添加的复杂语法
    面向对象中的设计陷阱
  • 原文地址:https://www.cnblogs.com/it-xcn/p/5698521.html
Copyright © 2011-2022 走看看