关于EF的三种分类----CodeFirst

时间:2021-10-03 17:45:02

新建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()]
[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();
}
}
}

搞定