Entity Framework 入门

来源:互联网 发布:网络硬盘录像机的设置 编辑:程序博客网 时间:2024/05/23 15:07
1、使用步骤

(1)EF 添加引用

(2)写实体类

public class Student{    [Key]    public int Id { get; set; }    [Required]    [StringLength(50)]    public string Name { get; set; }}

(3)包装代码,继承自 DbContext

public class StudentInfoEntities : DbContext{    public DbSet<Student> a { get; set; }}

(4)Db.tolist 实例化包装对象,执行后数据库将生成该表。

private StudentInfoleiEntities db = new StudentInfoEntities();db.a.ToList();

要添加 Student 数据时,执行

using (var db = new StudentInfoleiEntities()){    var studentInfo = new Student    {        Id = 123,        Name = "吴宗宪",    };    db.c.Add(studentInfo);    db.SaveChanges();}

(5)包装类名与 WebConfig,连接名一样。 

<connectionStrings>    <add name="StudentInfoEntities" connectionString="Data Source=.; User=sa;Password=sa;Initial Catalog=scoreDB;Integrated Security=True"  providerName="System.Data.SqlClient" /></connectionStrings>

 

2、EF 查询

(1)Ling to Entity

(2)基于方法的查询,Lamda 表达式

(3)原生 SQL 查询,对象名.sqlQuery("select ...")

 

3、多层架构,Repository 通过 ORM 或 SQL 把持久化数据转化成领域对象,然后根据业务逻辑对应领域层服务。

0 0
原创粉丝点击