标签:
技术的发展真是太快了,转眼间已经是第6个版本,现在抓紧时间学习一下!进入正题……
前提条件:
1.联网
2.平台:在Visual Studio 2013
3.数据库:SQL Server 2008R2
一、在项目中引入Entity Framework框架支持:
1.检查在项目中有没有引用EntityFramework和EntityFramework.SqlServer库文件;
2.如果没有则点击工具—NuGet程序包管理器—管理解决方案的NuGet程序包…
3.打开程序包管理界面搜索entity(如果没有安装过会显示“安装”按钮)点击安装即可
二、初步使用:
1.配置数据库连接
<connectionStrings> <add name="mydb" connectionString="Data Source=机器名\数据库服务名;Initial Catalog=abcc;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/> </connectionStrings>
2.新建一个EntityDB类并继承DbContext
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data.Entity; 7 using System.Data.Entity.ModelConfiguration; 8 namespace ConsoleEntity 9 { 10 public class EntityDB:DbContext 11 { 12 public EntityDB(): base("mydb") 13 { 14 15 } 16 public virtual DbSet<Person> Person{ get; set; } 17 18 19 20 } 21 public class Person 22 { 23 public int Id{get;set;} 24 public string Name{get;set;} 25 } 26 27 }
3.插入数据测试是否成功:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 6 Database.SetInitializer(new CreateDatabaseIfNotExists<EntityDB>()); 7 EntityDB db = new EntityDB(); 8 db.Person.Add(new Person { Id = 1, Name = "ddd" }); 9 db.SaveChanges();
10 var d = db.Person.ToList(); 11 foreach(var t in d) 12 Console.WriteLine(t.Name); 13 Console.ReadKey(); 14 } 15 }
如果屏幕出现“ddd”就是成功了,下次将讲解数据库生成策略!
标签:
原文地址:http://www.cnblogs.com/bhdblogs/p/4837423.html