之前曾经写过一篇文章,《EF创建Model层》,这篇文章采取的方式为ModeFirst。现在给大家来讲一下如何用EF_CodeFirst来生成数据库。
第一:打开VS,创建一个类库,并添加以下的引用。
第二:添加自己的实体类。例如:
<span style="font-size:18px;"> using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF_CodeFirst
{
public class AllUser
{
//用户ID
[Key]
public Guid AllUserId { get; set; }
//用户名
[Required]
public string UserName { get; set; }
//密码
[Required]
public string PassWord { get; set; }
//用户级别
[StringLength(300)]
public string UserType { get; set; }
}
}
</span>
其中,[Key]表示在数据库中该字段为主键,[Required]表示不为空,[StringLength]表示长度
第三:添加上下文类,继承Context,例如:
<span style="font-size:18px;"> using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF_CodeFirst
{
public class UserDbContext:DbContext
{
//无参构造函数
public UserDbContext()
: base("name=userDbContext")
{
this.Database.CreateIfNotExists();
}
//有参构造函数。用来动态创建库/切库
public UserDbContext(string connectionString)
: base(connectionString)
{
this.Database.CreateIfNotExists();
}
public DbSet<AllUser> AllUser { get; set; }
}
}
</span>
第四:如果使用上面的无参构造函数需要在配置文件中进行配置,例如:
<span style="font-size:18px;"> <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="userDbContext" connectionString="server=.;uid=sa;pwd=123456;database=ITOOceshi"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
</span>
配置文件中的<connectionString>节点下的name值与你所建的上下文类中的无参构造函数中的name值一致。
最后,在别的程序集进行调用:
<span style="font-size:18px;">UserDbContext db = newUserDbContext();//无参的</span>
这样就可以在数据库里面看到你所创建的数据库,名称为你在配置文件中写的database的名称。
另外:如果使用的有参构造函数,那么不需要写配置文件,只需在调用的时候给连接字符串connectionString赋值即可。
<span style="font-size:18px;">string connectionString = "DataSource=.;user id=sa;password=123456;persist security info=True;database="+ user.UserName; 这里的数据库名称自定义。
UserDbContext db2 = newUserDbContext(connectionString);//有参的</span>
最最后,希望本文能给大家带来一点帮助,也请大家做出批评指正。