zoukankan      html  css  js  c++  java
  • 关于EF的三种分类----CodeFirst

    新建StudentInfo.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CodeFirstDemo
    {
        public class StudentInfo
        {
            [Key]
            public int Id { get; set; }
            [StringLength(32)]
            [Required]
            public string StuName { get; set; }
            [Required]
            public DateTime SubTime { get; set; }
            public virtual ClassInfo ClassInfo { get; set; }
        }
    }

    这里的key是主键,stringlength是长度,required是必填项

    新建CodeFirstDbContext.cs继承DbContext

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CodeFirstDemo
    {
        public class CodeFirstDbContext:DbContext
        {
            public CodeFirstDbContext()
                : base("name=constr") 
            {
    
            }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            }
            public DbSet<ClassInfo> ClassInfo { get; set; }
            public DbSet<StudentInfo> StudentInfo { get; set; }
        }
    }

    增加连接串

    <connectionStrings>
        <add  name="constr" connectionString="server=192.168.1.184;uid=sa;pwd=123456;database=T9" providerName="System.Data.sqlClient" />
      </connectionStrings>

    配置生成数据库

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CodeFirstDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                CodeFirstDbContext db = new CodeFirstDbContext();
                //如果找不到数据库的话,就创建数据库
                db.Database.CreateIfNotExists();
                ClassInfo ClassInfo = new ClassInfo();
                ClassInfo.ClassName="0413班";
                ClassInfo.CreateTime=DateTime.Now;
                db.ClassInfo.Add(ClassInfo);
                db.SaveChanges();
                Console.ReadKey();
            }
        }
    }

    搞定

  • 相关阅读:
    c++析构函数、虚析构函数、纯虚析构函数详解
    php实现设计模式之 策略模式
    php实现设计模式之 简单工厂模式
    记录一下工作中碰到的一些有用的命令
    预估高并发下API服务器数量
    囧啊!!时间戳转化为时间出错php
    php 实现hash表
    php 中使用cURL发送get/post请求,上传图片,批处理
    redis虚拟内存
    redis主从同步
  • 原文地址:https://www.cnblogs.com/wyt007/p/6410058.html
Copyright © 2011-2022 走看看