关于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(); } } }
搞定
作者:一个大西瓜
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!