您的位置:首页 > 其它

Entity Framework5 code first 学习1

2013-06-06 09:22 309 查看
因为要学习Nopcommerce,就学习了EF5 CodeFirst。当初在Nopcommerce 1.9中是EF4,说实话对Linq to Entity 不大喜欢。如今却发现这个新技术有大行其道的趋势了。

拥抱变化吧。

Code First其宗旨大概是不用先建立数据库,不用EF4里的edmx配置文件,通过编码就可以建立数据库,操纵数据库。传统的开发方法一般都要先建数据库。

使用Code First,有两个有用的类:DBContext,DBSet。所属命名空间:System.Data.Entity。当然要引入一个EntityFramework.dll。

必须先建立一个DBContext的子类,去连接建立数据库。

DBSet 是一个实体的集合。

假如有这么个案例宠物医院收治患畜的业务模型。

public   class Patient
{

public Patient()
{

Visits = new List<Visit>();

}
public int Id { get; set; }

public string Name { get; set; }

public DateTime BirthDate { get; set; }
public AnimalType AnimalType { get; set; }
public DateTime FirstVisit { get; set; }
public List<Visit> Visits { get; set; }

}


定义这样一个实体,将要映射到数据库中,成为一个表。看看这个定义,有经验的人会问到:

主键是哪个字段?Name这个字段长度是多少?你猜对了,这个定义还少了一些东西,用于对实体进行限定。

限定实体有两种方式: DataAnnotations 和 Fluent API。前者简单,后者有点繁琐,但是后者可以做一些前者做不到的事情。

实体在使用DataAnnotations定义数据库和验证,要引入这两个namespace:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


主要的DataAnnotationAttribute有这么几个:

[Key]

数据库: 定义主键

[Required]

数据库: 会把字段设置成not null

验证: 会要求必须输入

是否可以为null [Required(AllowEmptyStrings = false)] 不能为null和空字符串

[MaxLength] [MinLength]

[ForeignKey("列名")]

这个是定义外键的。

定义好实体之后,DBContext和dbset出场。

public class VetContext : DbContext
{
public VetContext(string contstr):base(contstr)
{
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; }

}


  注意VetContext的构造函数,参数是数据库连接串,好像SqlConnection哦,

private static void CreateNewPatient()
{
var dog = new AnimalType { TypeName = "Dog" };
var patient = new Patient

{

Name = "Sampson",
BirthDate = new DateTime(2008, 1, 28),
FirstVisit = new DateTime(2011,1,1),
AnimalType = dog,
Visits = new List<Visit>{
new Visit{Date = new DateTime(2011, 9, 1)}
}

};

using (var context = new VetContext("Data Source=localhost;Initial Catalog=EFTest;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=aa;MultipleActiveResultSets=True"))
{

context.Patients.Add(patient);//将实体添加到集合中
context.SaveChanges();//修改数据库

}

}
static void Main(string[] args)
{
CreateNewPatient();
}


  

例子附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: