公司一直在用ADO.net + Entity + 代码自动生成器的方式操作数据库,哎~~(每次手写SQL,感觉跟不上时代了) 每次添加删除字段该无数个查询函数,真的很蛋疼!!决心自己研究下ORM,先从EF code first入手吧 !! 在这里记一笔可以以后自己学习,下面是我在学习过程及遇到的问题。开发环境VS2013 .net framework4.0
1、首先当然是先用nuget引入最新的Entity framework程序包,在这儿就遇到了问题自带的nuget.org程序包在我这儿就是连接不上,网上好多方法都试过(加硬解等等)后来发现nuget.org的地址是HTTPS的 访问http://www.nuget.org/api/v2/么得问题,最后只能自己添加源信息
获取程序包成功,下面安装引入OK了,配置文件里多了如下东东
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<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>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
2、下面当然是定义数据库连接串,创建数据库上下文了
<connectionStrings>
<add name="StudyDB" connectionString="data source=127.0.0.1;database=Study;uid=sa;pwd=92923;"/>
</connectionStrings>
class StudyContext : DbContext
{
public StudyContext()
: base(ConfigurationManager.ConnectionStrings["StudyDB"].ToString())
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
3、创建实体,在数据库上下文中添加创建实体的实例
class Teacher
{
/// <summary>
/// 主键
/// </summary>
public string ID { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public string Age { get; set; }
/// <summary>
/// 所交专业
/// </summary>
public string CourseID { get; set; }
}
class StudyContext : DbContext
{
public StudyContext()
: base(ConfigurationManager.ConnectionStrings["StudyDB"].ToString())
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// 教师表
/// </summary>
DbSet<Teacher> Teachers { get; set; }
}
4、数据库本来没有创建好,写完一个数据库操作,数据库自动生成 很神奇的赶脚!!(下面是增删改查的样例简单版 都是单表查询)
static void Main(string[] args)
{
using (StudyContext context = new StudyContext())
{
//添加
context.Teachers.Add(new Teacher { ID = "2",CourseID = "2",Age = "24",Name = "Jim"});
context.SaveChanges();
//修改
Teacher teacher1 = context.Teachers.Where(e => e.ID == "2").Single();
teacher1.Name = "Lily";
context.SaveChanges();
//删除
Teacher teacher2 = context.Teachers.Where(e => e.ID == "1").Single();
context.Teachers.Remove(teacher2);
context.SaveChanges();
//查询
IQueryable<Teacher> teachers = context.Teachers.Where(e => 1 == 1);
if (teachers == null || teachers.Count() <= 0)
{
Console.WriteLine("无数据");
}
else
{
foreach(Teacher item in teachers)
{
Console.WriteLine(item.Name);
}
}
Console.ReadLine();
}
}
5、如果我们改了实体我们,数据库也会跟着改动,前提是做一些设置,有三种方法,挑选了一种企业开发中比较稳妥的方法来做,用migrations手动进行更新。
1、在程序包控制台中输入enable-migrations命令,自动数据库迁移,目录中会产生名称为Migrations的文件夹
2、在Migrations的文件夹中修改Configuration.cs,修改代码如下(可自行选择):
public Configuration()
{
AutomaticMigrationDataLossAllowed = true;//实体去掉属性后同步数据库是否允许删除数据
AutomaticMigrationsEnabled = true;//迁移数据库
ContextKey = "EFStudy.DB.StudyContext";
}
3、在程序包控制台中输入update-database命令,数据库表中添加的列
(注:如果默认不迁移数据库不做任何更改,实体更改后,使用EF的时候报错:The model backing the 'StudyContext' context has changed since the database was created. Consider using Code First Migrations to update the database)
6、再来个连表查询的例子
static void Main(string[] args)
{
using (StudyContext context = new StudyContext())
{
context.Courses.Add(new Course(){ ID = "2",teacherID = "2",CourseName = "数学",CreateTime = DateTime.Now});
context.SaveChanges();
//连表查询
var teacherTeachList = from tItem in context.Teachers
join cItem in context.Courses
on tItem.CourseID equals cItem.ID
where tItem.ID == "2"
select new { tItem.Name,cItem.CourseName};
if (teacherTeachList == null || teacherTeachList.Count() <= 0)
{
Console.WriteLine("无数据");
}
else
{
foreach (var item in teacherTeachList)
{
Console.WriteLine(item.Name);
Console.WriteLine(item.CourseName);
}
}
Console.ReadLine();
}
}