关于NHibernate、LINQ、Entity Framework
NHibernate采用非侵入式的方式进行对象-关系映射,从而成就了其轻量级ORM技术的美名,这一点相信成为很多架构师钟爱他的重要理由。NHibernate技术架构如下图所示:
NHibernate的使用大致可以分为配置信息、编写映射文件和持久化数据几个步骤:
一、配置信息
NHibernate需要对配置文件作以下配置方可使用:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> </configSections> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.connection_string">Data Source=localhost;User Id=sa;Password=11111111;Initial Catalog=Apollo;MultipleActiveResultSets=True;</property> <mapping assembly="Apollo.Blog.EF.Chapter1.Domain" /> </session-factory> </hibernate-configuration> </configuration>
二、映射文件
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Apollo.Blog.EF.Chapter1.Domain" namespace="Apollo.Blog.EF.Chapter1.Domain"> <class name="User" table="`User`" lazy="false"> <id name="ID"> <generator class="guid" /> </id> <property name="Name" type="string" not-null="true" /> </class> </hibernate-mapping>
三、数据持久化
1 var sessionFactory = new Configuration().Configure().BuildSessionFactory(); 2 using (var session = sessionFactory.OpenSession()) 3 { 4 session.Save(user); 5 session.Flush(); 6 }
LINQ(Language Integrated Query,语言集成查询)是一组用于C#和VB.NET语言的扩展,它允许编写C#或者VB.NET代码以查询数据库相同的方式操作内存数据。LINQ提供提供了丰富的类似SQL的查询语法,功能强大且容易上手。
LINQ技术通过提供程序扩展,可以实现对任何数据源的访问。常用的提供程序有LINQ to SQL、LINQ to XML、LINQ to Objects、LINQ to Entities、LINQ to Datasets、LINQ to ADO.NET。LINQ技术架构如下图所示:
LINQ的使用大致包括连接配置、关系映射、上下文环境定义和数据持久化四步:
一、连接配置
LINQ的数据库连接配置与ADO.NET一样:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="AdoNet" connectionString="Data Source=localhost;User Id=sa;Password=11111111;Initial Catalog=Apollo;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
二、侵入式关系映射
[Table(Name = "User")] public class LinqUser : User { [Column(IsPrimaryKey = true)] public override Guid ID { get; set; } [Column] public override string Name { get; set; } }
三、上下文环境
internal class LinqContext : DataContext { public LinqContext(string connection) : base(connection) { } public LinqContext(IDbConnection connection) : base(connection) { } public Table<LinqUser> Users { get { return this.GetTable<LinqUser>(); } } }
四、数据持久化
1 using (var db = new LinqContext(CONNECTION_STRING)) 2 { 3 db.Users.InsertOnSubmit(user); 4 db.SubmitChanges(); 5 }
Entity Framework的全称为ADO.NET Entity Framework,是在ADO.NET上层实现的ORM封装,其技术架构如下图所示:
Entity Framework的使用与LINQ一样,分为连接配置、关系映射、上下文环境定义和数据持久化四步:
一、连接配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="EntityFramework" providerName="System.Data.EntityClient" connectionString="provider=System.Data.SqlClient; provider connection string=" Data Source=localhost; User Id=sa; Password=11111111; Initial Catalog=Apollo; Integrated Security=False; MultipleActiveResultSets=True;"; metadata=..\..\..\Apollo.Blog.EF.Chapter1.Domain\Edmx\Chapter1.ssdl| ..\..\..\Apollo.Blog.EF.Chapter1.Domain\Edmx\Chapter1.csdl| ..\..\..\Apollo.Blog.EF.Chapter1.Domain\Edmx\Chapter1.msl"/> </connectionStrings> </configuration>
二、关系映射
Entity Framework是通过定义概念模型(CSDL)、物理模型(SSDL)及两者的映射关系(MSL),实现对象与关系映射的。
SSDL映射文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="Chapter1.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"> <EntityContainer Name="Chapter1StoreContainer"> <EntitySet Name="User" EntityType="Chapter1.Store.User" store:Type="Tables" Schema="dbo" /> </EntityContainer> <EntityType Name="User"> <Key> <PropertyRef Name="ID" /> </Key> <Property Name="ID" Type="uniqueidentifier" Nullable="false" /> <Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="40" /> </EntityType> </Schema>
CSDL映射文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="Chapter1" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"> <EntityContainer Name="Chapter1" annotation:LazyLoadingEnabled="true"> <EntitySet Name="User" EntityType="Chapter1.User" /> </EntityContainer> <EntityType Name="User"> <Key> <PropertyRef Name="ID" /> </Key> <Property Name="ID" Type="Guid" Nullable="false" /> <Property Name="Name" Type="String" Nullable="false" /> </EntityType> </Schema>
MSL映射文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs"> <Alias Key="Cdm" Value="Chapter1" /> <Alias Key="Storage" Value="Chapter1.Store" /> <EntityContainerMapping CdmEntityContainer="Chapter1" StorageEntityContainer="Chapter1StoreContainer"> <EntitySetMapping Name="User"> <EntityTypeMapping TypeName="Cdm.User"> <MappingFragment StoreEntitySet="User"> <ScalarProperty Name="ID" ColumnName="ID" /> <ScalarProperty Name="Name" ColumnName="Name" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> </EntityContainerMapping> </Mapping>
三、上下文环境
Entity Framework提供了ObjectContext上下文环境,以对数据对象进行持久化操作。通过继承它,可以方便的实现自定义数据对象的访问。
internal class EntityContext : ObjectContext { public EntityContext() : this("name=EntityFramework") { } public EntityContext(string connectionString) : base(connectionString, "Chapter1") { this.Users = CreateObjectSet<User>(); } public ObjectSet<User> Users { get; set; } }
四、数据持久化
1 using (var db = new EntityContext()) 2 { 3 db.Users.AddObject(user); 4 db.SaveChanges(); 5 }