1—首先在程序中建立表
在Model文件夹中建立表PersonModel。
引入2个空间
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
实体类定义
[Table("T_user")]
public class Person
{
[Key]
public int Fid { get; set; }
[StringLength(100)]
[Required(ErrorMessage="请输入姓名")]
public string Fname { get; set; }
[StringLength(20)]
public string Fsex { get; set; }
public int Fage { get; set; }
[StringLength(200)]
public string Faddress { get; set; }
[StringLength(100)]
public string Fphone { get; set; }
}
2—写入app.config连接字符串
<configuration>
<!-- 使用EF框架 -->
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<!-- 数据库连接参数 -->
<connectionStrings>
<add name="myDbConn" connectionString="Data Source=vpc05;Initial Catalog=ef1-2;Persist Security Info=True;user id=sa;password=****" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
3—建立DAL数据库存取类
/*
* 数据库上下文
* 继承自DbContext
*/
public class myDbDAL:DbContext
{
static myDbDAL()
{
Database.SetInitializer<myDbDAL>(new DropCreateDatabaseIfModelChanges<DbContext>() );
}
public myDbDAL()
: base("name=myDbConn")
{
//name取值自App.config中的add name值
}
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().ToTable("T_user");
base.OnModelCreating(modelBuilder);
}
}