.NET:Entity Framework 6.1笔记
EF6越来越完善,跟主流的Hibernate等ORM框架越来越接近了,先看下Entity类的定义:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EFSample.Model { [Table("T_ORDER")] public class Order { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { set; get; } [StringLength(50)] [Column("CUSTOMER_NAME")] public String CustomerName { set; get; } [Column("AMOUNT")] public decimal Amount { set; get; } public virtual ICollection<OrderItem> OrderItems { set; get; } } }
1 using System; 2 using System.ComponentModel.DataAnnotations; 3 using System.ComponentModel.DataAnnotations.Schema; 4 5 namespace EFSample.Model 6 { 7 [Table("T_ORDER_ITEM")] 8 public class OrderItem 9 { 10 [Key] 11 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 12 public int ID { set; get; } 13 14 [ForeignKey("Order")] 15 [Column("ORDER_ID")] 16 public int OrderID { set; get; } 17 18 [StringLength(50)] 19 [Column("PRODUCT_NAME")] 20 public String ProductName { set; get; } 21 22 [Column("PRICE")] 23 public Decimal Price { set; get; } 24 25 [Column("QUANTITY")] 26 public int Quantity { set; get; } 27 28 public virtual Order Order { set; get; } 29 30 31 } 32 }
光看Attribute,已经跟Hibernate的Annotation很相似了。
配置文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <section name="entityFramework" 5 type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> 6 </configSections> 7 8 <entityFramework> 9 <contexts> 10 <context type="EFSample.DAL.OrderContext, EFSample" disableDatabaseInitialization="false"> 11 <databaseInitializer type="EFSample.DAL.OrderInitializer, EFSample" /> 12 </context> 13 </contexts> 14 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 15 <parameters> 16 <parameter value="v11.0" /> 17 </parameters> 18 </defaultConnectionFactory> 19 <providers> 20 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 21 </providers> 22 </entityFramework> 23 24 <startup> 25 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" /> 26 </startup> 27 28 <connectionStrings> 29 <!--连接字符串,使用SQLSERVER LocalDb--> 30 <add name="MyConn" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=OrderDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> 31 </connectionStrings> 32 33 </configuration>
注:LocalDb在开发阶段很方便,但是试用中有一个小问题,如果把生成的mdf物理文件删除后,再次运行总是报错(不知道是不是个别现象),只能把Initial Catalog=OrderDatabase中的文件名改成其它名称(比如:Catalog=OrderDb),才能正常运行。
此外,NuGet Package Manager工具搞得象java的maven一样,可以自动联机下载所需的依赖项,Tools->NuGet Package Manager
输入
Install -Package EntityFramework
就能自动向project添加相关的dll引用
DbContext
1 using EFSample.Model; 2 using System.Data.Entity; 3 using System.Data.Entity.ModelConfiguration.Conventions; 4 5 namespace EFSample.DAL 6 { 7 public class OrderContext:DbContext 8 { 9 public OrderContext() : base("MyConn") { } 10 11 public DbSet<Order> Orders { set; get; } 12 13 public DbSet<OrderItem> OrderItems { set; get; } 14 15 protected override void OnModelCreating(DbModelBuilder modelBuilder) 16 { 17 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 18 } 19 } 20 }
示例代码:
1 using EFSample.DAL; 2 using EFSample.Model; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 7 namespace EFSample 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 using (var db = new OrderContext()) 14 { 15 16 //直接执行Sql语句 17 db.Database.ExecuteSqlCommand("delete from t_order"); 18 19 var orders = new List<Order>(){ 20 new Order{ CustomerName="jimmy.yang",Amount=200, OrderItems=new List<OrderItem>(){ 21 new OrderItem(){ Price=10, Quantity=20, ProductName="Mobile"} 22 }}, 23 new Order{ CustomerName="杨俊明",Amount=300, OrderItems=new List<OrderItem>(){ 24 new OrderItem(){ Price=15, Quantity=20, ProductName="架构之美"} 25 }}}; 26 27 //批量添加记录 28 db.Orders.AddRange(orders); 29 30 //提交到db 31 db.SaveChanges(); 32 33 //查询 34 var query = db.Orders.Where(c => c.CustomerName == "Jimmy.yang").AsQueryable(); 35 36 //输出Sql语句 37 Console.WriteLine(query.ToString()); 38 39 List<Order> orderEntities = query.ToList(); 40 41 foreach (var order in orderEntities) 42 { 43 Console.WriteLine(String.Format("ID:{0}/CustomerName:{1}/Amount:{2}/ItemCount:{3}", order.ID, order.CustomerName, order.Amount,order.OrderItems.Count)); 44 } 45 } 46 47 Console.WriteLine("ok!"); 48 Console.Read(); 49 } 50 } 51 }
输出:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[CUSTOMER_NAME] AS [CUSTOMER_NAME],
[Extent1].[AMOUNT] AS [AMOUNT]
FROM [dbo].[T_ORDER] AS [Extent1]
WHERE N‘Jimmy.yang‘ = [Extent1].[CUSTOMER_NAME]
ID:9/CustomerName:jimmy.yang/Amount:200/ItemCount:1
ok!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。