1.新建空项目
2.创建实体类库
创建实体
public class ClassInfo { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增 public int SeqNum { get; set; } [Key,MaxLength(50)] public string ClassID { get; set; } //[Required]必填 [Required, MaxLength(50)] public string ClassName { get; set; } [MaxLength(255)] public string Disc { get; set; } } public class UsersInfo { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增 public int SeqNum { get; set; } [Key,MaxLength(50)] public string UserID { get; set; } //[Required]必填 [Required,MaxLength(50)] public string UserName { get; set; } [MaxLength(1)] public int Gender { get; set; } [MaxLength(50)] public string BelongClass { get; set; } [MaxLength(255)] public string Disc { get; set; } }
3.再创建一个类库项目
创建DemoContext类(与数据库交互)
public class DemoContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( connectionString: "server=.;database=MyTestDB;uid=sjz2018dbuser;pwd=1ECD9E*#E9DCE1;" ); } public DbSet<ClassInfo> ClassInfos { get; set; } public DbSet<UsersInfo> UsersInfos { get; set; } }
所引nuget包
4.测试结果
新建一个控制台,测试。
static void Main(string[] args) { //用完即释放 using var db = new DemoContext(); var c = new ClassInfo { ClassID = "10001", ClassName = "三年级一班" }; db.ClassInfos.Add(c); var count = db.SaveChanges(); Console.WriteLine(count); }