首页| JavaScript| HTML/CSS| Matlab| PHP| Python| Java| C/C++/VC++| C#| ASP| 其他|
购买积分 购买会员 激活码充值

您现在的位置是:虫虫源码 > 其他 > EF Code First简介及一个入门级实例

EF Code First简介及一个入门级实例

  • 资源大小:1.82M
  • 上传时间:2021-07-26
  • 下载次数:0次
  • 浏览次数:0次
  • 资源积分:1积分
  • 标      签: C#语言基础

资 源 简 介

一、EF Code First简介 EntityFramework 代码优先   二、EF Code First第一个简单实例 1、开发环境及数据库说明 开发环境:Visual Studio 2010 Ultimate sp1 Sql Server 2008 R2 数据库:Northwind 2、实例代码结构 结构说明: App:控制台应用程序 Data:数据访问 Domain:实体类 3、安装Entity Framework   在Visual Studio编辑器中点击Tools -> Library Package Manager -> Package Manager Console,在Package Manager Console窗口中执行下面语句,安装最新版Entity Framework。 PM> Install-Package EntityFramework   App层和Data层分别添加对EntityFramework的引用:     在App层安装EntityFramework之后,将自动添加App.config和packages.config文件。   App.config配置Entity Framework版本信息及数据库连接信息,修改其中数据连接信息以适应本地实际环境。 1 2 3 4 5
6 7 8 9 10 11 12 13 14 15   packages.config现实当前项目使用的package: 1 2 3 4 4、实例代码 Domain中Category.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Northwind.Domain.Entities 7 { 8 public class Category 9 { 10 /// 11      /// 分类ID 12      /// 13 public int CategoryID { get; set; } 14 15 /// 16      /// 分类名称 17      /// 18 public string CategoryName { get; set; } 19 } 20 } Data中NorthwindContext.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.Data.Entity; 7 8 using Northwind.Domain.Entities; 9 10 namespace Northwind.Data 11 { 12 public class NorthwindContext : DbContext 13 { 14 public DbSet Categories { get; set; } 15 } 16 } App中Program.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using Northwind.Data; 7 using Northwind.Domain.Entities; 8 9 namespace Northwind.App 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Category c = new Category() { CategoryName = "电子数码" }; 16 17 using (NorthwindContext db = new NorthwindContext()) 18 { 19 db.Categories.Add(c); 20 db.SaveChanges(); 21 } 22 23 Console.WriteLine("Finish"); 24 Console.ReadKey(); 25 } 26 } 27 } 5、运行说明   由于在上面的数据库连接字符串中并未包含指定的数据库名称,运行成功之后,将在本地数据引擎中创建如下数据库和表:   数据库名称:Northwind.Data.NorthwindContext   表名称:Categories 6、示例代码附件
VIP VIP
0.185352s