• 使用asp.net mvc + entityframework + sqlServer 搭建一个简单的code first项目


    步骤:

    1. 创建一个asp.net mvc 项目

    1.1 项目创建好结构如下

    2 通过vs安装EntityFramework框架

    install-package entityframework

     3. 创建一个继承DBContext的 MyContext类,并引用命名空间  using System.Data.Entity;

    3.2 创建一个构造函数,并且实现OnModelCreating方法

    public class MyContext:DbContext
    {
      public MyContext() : base("Data Source=.;Initial Catalog=test;Integrated Security=True") { } // 注:这是连接sqlserver字符串,具体到时候可以放在配置文件中
    
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
        base.OnModelCreating(modelBuilder);
      }
    }

    4. 创建一个person模型实体类,这个的字段要和表的字段对应,也就是说你希望将来表中有哪些类型的字符,那么就在这个类中定义好这些类型字段

    (这里为了简便我就定义两个字符)

    public class Person
    {
      public int Id { get; set; }  // 使用codefirst这个字符会帮我实现默认自动增长
      public string Name { get; set; }
    }

     5. 在MyContext中将这个实体模型类添加进去,以便将来与数据库中的表对应解析

     public DbSet<Person> Persons { get; set; }

     

    6. 创建一个继承EntityTypeConfiguration的PersonConfig类,用于配置,具体实现如下:

    引用命名空间 using System.Data.Entity.ModelConfiguration;

    public class PersonConfig:EntityTypeConfiguration<Person>
    {
      public PersonConfig()
      {
        this.ToTable("Persons"); // 这是代表将来数据库中表的名字
      }
    }

     7. 在Mycontext中的OnModelCreating添加下面代码 ,并引用命名空间 using System.Reflection;

    modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());

     

    8 创建一个Home控制器,添加一个数据测试下

    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            using (MyContext ctx = new MyContext())
            {
                Person p = new Person();
                p.Name = "yjc";
                ctx.Persons.Add(p);
    
                ctx.SaveChanges();
            }
            return Content("添加成功");
        }
    }                            

     

    9 打开SQL server查看

  • 相关阅读:
    CentOS 7中firewall防火墙详解和配置以及切换为iptables防火墙
    使用kubeadm安装Kubernetes v1.10
    Docker版本变化和新版安装
    Kubernetes实践--hello world 示例
    kubernetes常用命令
    区块链入门教程
    Json概述以及python对json的相关操作
    linux activiti5.22 流程图乱码
    Spring Cloud Gateway 实现Token校验
    oauth table
  • 原文地址:https://www.cnblogs.com/itcastai/p/9878955.html
Copyright © 2020-2023  润新知