entity framework6出来之后,.net下的code first渐入佳境。数据的升级更加方便了,这个很重要。
今天简单讲一下code first的过程。
首先,安装entity framework。这个借助nuget很方便;
其次,创建model,诸如下面的代码
class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
这里带ID的属性默认就是自增列,并且也是主键
再次,创建context,如下
class UserContext:DbContext
{
public UserContext() : base("default") { }
public DbSet<User> Users { get; set; }
}
这里的default就是配置文件中数据库连接字符串的名字
接着,修改配置文件,添加数据库连接字符串
<connectionStrings>
<add name="default" connectionString="server=(local);uid=sa;pwd=xxx;database=user" providerName="System.Data.SqlClient"/>
</connectionStrings>
这里providerName别忘了。
最后,在代码中调用
UserContext uc = new UserContext();
User u = new User();
u.Name = textBox1.Text;
u.UserName = textBox2.Text;
u.Password = textBox3.Text;
uc.Users.Add(u);
uc.SaveChanges();
最后之后,运行,所有填写的内容都会存到数据库中。