》对于应用程序行业领域来说,涉及到Net框架的,在众多支持大型项目的商用ORM框架中,使用最多的目前了解的主要有三款:

1、NHibernate(从Java版移植来的Net版)、

2、微软的EF、

3、还有就是今天提到的LLBLGen

》ORM之间的性能比较

从上图的测试结果可以看出,传统的手动编写代码访问数据库,例如手动编写的ADO.NET,仍然是从数据库中取值的最快捷的方式,性能依然最好。而相比于三大ORM框架来说由于NH的功能庞大EF的次之,LLBLGen相较于来说性能最好。当然对比ORM访问数据库的性能这一个侧面并不能完全说明一切,缓存机制、延迟加载机制的配合使用已经可以大部分避免数据库访问性能损耗的影响。(题外话:既然传统如Ado.net的访问方式依然性能优异为何还要选用ORM的话题不做扩展)

》LLBLGen Pro是LLBLGen的数据库访问解决方案,她包含两个部分:设计器(LLBLGen Pro designer)和运行时框架(LLBLGen Pro runtime framework).

》设计器生成的源码除支持自身的运行时框架外,还支持另外三种数据库映射框架产品:

  • Entity Framework 1.0和4.0
  • NHibernate 2.x:包括标准的Hibernate和Fluent NHibernate
  • LINQ to SQL

》LLBLGen Pro支持的数据库种类众多:诸如MS Access 2000/XP/2003/2007/2010、SQL Server 2000/2005/2008/2008R2/Express/MSDE/SQL Server CE Desktop、Oracle 9i/10g/11g、PostgreSql 7.4+/8.x+、Firebird 1.5.x/2.x、IBM DB2 7.x/8.x/9.x(非AS/400)、MySql 4.x,5.x (使用Core Lab/DevArt MySql .NET提供器)、Sybase Adaptive Server Enterprise(ASE)/SQL iAnywhere(ASA)。主流的几大数据库基本都包含在内,所有其框架适应数据库的兼容能力自然可不必太担心,同一套源码可以同时支持多种数据库,而不需要额外花太多精力考虑代码数据库兼容问题。

》LLBLGen的详细了解可访问官网 http://www.llblgen.com/  各种介绍资料、文档和代码示例均有

》在建立完业务模型并转化为规范的数据库实体后,LLBLGen框架的使用可以基本使你完全脱离繁琐的数据存储及展现查询的各种操作过程,而专心于业务逻辑的开发。

》以LLBLGen Pro runtime framework自身的运行时框架为例,设计器的代码生成自动将各种表视图存储过程等对于的视图模型Entidy、接口Interface、操作类等完整生成。业务中仅关心调用即可.

常用代码整理如下:

using SD.LLBLGen.Pro.ORMSupportClasses;

using FactoryClasses;

using HelperClasses;

using RelationClasses;

using DBAdapter;

using EntityClasses;

using ViewClasses;

namespace ORM_Demo{
  public class BLLCFUser:IBLLCFUser{     按照规则自动生成的方法代码,如下示例...(借鉴内部资料的整理)
  }
} 、视图查询 例: Select * From View_CF_User_All Where RecordStatus<>'InActive' Order By UserID Desc
public ViewCFUserAllTypedView FetchAllUser()
{
DataAccessAdapter adapter = new DataAccessAdapter();
try
{
ViewCFUserAllTypedView user = new ViewCFUserAllTypedView();
RelationPredicateBucket bucket = new RelationPredicateBucket();
SortExpression sorter = new SortExpression();
//加过滤条件
bucket.PredicateExpression.Add(ViewCFUserAllFields.RecordStatus != "InActive");
//加排序条件
sorter.Add(ViewCFUserAllFields.UserID | SortOperator.Descending);
adapter.FetchTypedView(user.GetFieldsInfo(), user, bucket, , sorter, true);
return user;
}
catch
{
return null;
}
finally {
adapter.Dispose();
} } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo();
ViewCFUserAllTypedView user = orm.FetchAllUser();
if (user != null)
{
gridView.DataSource = user;
gridView.DataBind();
} 、表(记录集合)查询
例: Select * From CF_User
public EntityCollection<DerivedCFUserEntity> FetchUser()
{
DataAccessAdapter adapter = new DataAccessAdapter();
try
{
EntityCollection<DerivedCFUserEntity> user = new EntityCollection<DerivedCFUserEntity>(new DerivedCFUserEntityFactory());
RelationPredicateBucket bucket = new RelationPredicateBucket();
SortExpression sorter = new SortExpression();
adapter.FetchEntityCollection(user, bucket, , sorter);
return user;
}
catch
{
return null;
}
finally
{
adapter.Dispose();
}
} 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo();
EntityCollection<DerivedCFUserEntity> user = orm.FetchUser();
if (user != null)
{
gridView.DataSource = user;
gridView.DataBind();
} 、表(某一记录)查询
例: Select * From CF_User Where LoginName='Admin' And RecordStatus<>'Inactive'
public DerivedCFUserEntity FetchUserInfo(string loginName)
{
DataAccessAdapter adapter = new DataAccessAdapter();
try
{
DerivedCFUserEntity user = new DerivedCFUserEntity();
RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.PredicateExpression.Add(CFUserFields.LoginName == loginName);
bucket.PredicateExpression.AddWithAnd(CFUserFields.RecordStatus != "Inactive");
user = (DerivedCFUserEntity)adapter.FetchNewEntity(new DerivedCFUserEntityFactory(), bucket);
return user;
}
catch
{
return null;
}
finally
{
adapter.Dispose();
} } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo();
DerivedCFUserEntity user = orm.FetchUserInfo("Admin");
if (user.UserID>)
{
lblLoginName.Text = user.LoginName;
} -、多表(多表查询 Linq实现) 》》
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
LinqMetaData metaData = new LinqMetaData(adapter);
var q = from t1 in metaData.CFEmployee
join t2 in metaData.CFCompany on t1.CompanyID equals t2.CompanyID
where t1.CompanyID <
select new { Addr = (t2.IRDAddress ?? "No Address"), t2.CreateUserID };
}
相当于
select IsNull(t2.IRDAddress,"No Address"),t2.CreateUserID
from CFEmployee as t1
inner join CFCompany as t2 on t1.CompanyID = t2.CompanyID
where t1.CompanyID < 》》
using (DataAccessAdapter adapter = new DataAccessAdapter()) { List<int> ids = new List<int>() { , , }; LinqMetaData metaData = new LinqMetaData(adapter); var q = from t1 in metaData.CFUser where ids.Contains(t1.UserID) select t1; } 等同于SELECT * FROM CF_USER WHERE USERID IN (, , ) 》》 using (DataAccessAdapter adapter = new DataAccessAdapter())
{
LinqMetaData metaData = new LinqMetaData(adapter);
var q = from t1 in metaData.CFUser
join t2 in metaData.CFEmployee on
new { C = t1.RefRecordID, B = t1.CreateUserID }
equals new { C = t2.EmployeeID, B = t2.CreateUserID }
join t3 in metaData.CFAccount on
new { D = t1.CreateUserID, E = t1.ModifyUserID }
equals new { D = t3.CreateUserID, E = t3.ModifyUserID }
select t1;
} 等同于 SELECT LPA_L1.* FROM [CF_User] as [LPA_L1]
INNER JOIN [CF_Employee] as [LPA_L2]
ON ( [LPA_L1].[RefRecordID] = [LPA_L2].[EmployeeID] AND [LPA_L1].[CreateUserID] = [LPA_L2].[CreateUserID]))
INNER JOIN [CFAccount] as [LPA_L3]
ON ( [LPA_L1].[CreateUserID] = [LPA_L3].[CreateUserID]) AND [LPA_L1].[ModifyUserID] = [LPA_L3].[ModifyUserID]) 、Insert操作(单表记录新增) 例: Insert CF_User(A,B,C) Values(……) public bool Add(string loginName, string password) {
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{
DerivedCFUserEntity user = new DerivedCFUserEntity();
user.PrivClassID = ;
user.RefTable = "CF_Employee";
user.RefRecordID = ;
user.LoginName = loginName;
user.Password = password;
user.LanguageSelect = "CN";
user.IsManager = "N";
user.RegionalSetting = "zh-CN";
user.RecordStatus = "Active";
user.CreateUserID = ;
user.CreateDate = DateTime.Now;
user.ModifyUserID = ;
user.ModifyDate = DateTime.Now;
adapter.SaveEntity(user);
adapter.Commit();
return true;
}
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose();
} } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo(); string loginName = "Amdin";
string password = ""; if (orm.Add(loginName, password))
{
Alert("Success");
}
else
{
Alert("Fail");
} 、Update操作(单表记录修改) 例: Update CF_User Set RecordStatus='Inactive' Where UserID= //主键条件 public bool Modify(int userID)
{
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{
DerivedCFUserEntity user = new DerivedCFUserEntity(userID);
if (user.UserID < )
{
return false;
}
else
{
user.IsNew = false;
adapter.FetchEntity(user);
user.RecordStatus = "Inactive";
adapter.SaveEntity(user);
adapter.Commit();
return true;
} }
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose();
} } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo();
int userID = ;
if (orm. Modify(userID))
{
Alert("Success");
}
else
{
Alert("Fail");
} Update操作(单表按条件多条记录修改) 例: Update CF_User Set RecordStatus='Inactive',ModifyDate=getdate() Where LoginName='Admin' and IsManager='N' //非主键条件
public bool Modify(string LoginName,string IsManager)
{
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{
RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.PredicateExpression.Add(DerivedCFUserFields.LoginName == LoginName);
bucket.PredicateExpression.Add(DerivedCFUserFields.IsManager == IsManager); DerivedCFUserEntity updateValues = new DerivedCFUserEntity();
updateValues.RecordStatus = HRRecordStatus.Inactive;
updateValues.ModifyDate = DateTime.Now; int AmountUpdated = adapter.UpdateEntitiesDirectly(updateValues, bucket); adapter.Commit();
return true;
}
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose();
} } 、Delete操作(单表记录删除) 例: Delete From CF_User Where UserID= public bool Delete(int userID) {
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{
DerivedCFUserEntity user = new DerivedCFUserEntity(userID);
if (user.UserID < )
{
return false;
}
else
{
adapter.FetchEntity(user);
//进行删除操作
adapter.DeleteEntity(user);
adapter.SaveEntity(user);
adapter.Commit();
return true; } }
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose(); } } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo(); int userID = ; if (orm.Delete(userID)) { Alert("Success"); } else { Alert("Fail"); } Delete操作(单表按条件多条记录删除) 例: Delete From CF_User Where CompanyID= and DeptID= public bool Delete(int CompanyID,int DeptID) {
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{
RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.PredicateExpression.Add(DerivedCFUserFields.CompanyID == CompanyID);
bucket.PredicateExpression.Add(DerivedCFUserFields.DeptID == DeptID); int AmountUpdated = adapter.DeleteEntitiesDirectly(typeof(DerivedCFUserEntity), bucket);
adapter.Commit();
return true;
}
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose(); } } 、Insert操作(多表记录新增) 例: Insert CF_Employee(…………………………) Values(……………………………………) Insert CF_User(…………………………) Values(……………………………………) public bool Add(string loginName, string password, string firstName, string lastName, string employeeNo) { DataAccessAdapter adapter = new DataAccessAdapter(); adapter.StartTransaction(IsolationLevel.ReadCommitted, ""); try { int employeeID; //再保存CF_Employee的信息 DerivedCFEmployeeEntity employee = new DerivedCFEmployeeEntity(); employee.FirstName = firstName; employee.LastName = lastName; employee.EmployeeNo = employeeNo; employee.ActingSupervisor = "N"; employee.IsAllowProxy = "N"; employee.DefaultLanguage = "CN"; employee.RecordStatus = "Active"; employee.CreateUserID = ; employee.CreateDate = DateTime.Now; employee.ModifyUserID = ; employee.ModifyDate = DateTime.Now; adapter.SaveEntity(employee, true); //保存CF_Employee后获取出EmployeeID
employeeID = employee.EmployeeID; //再保存CF_User的信息 DerivedCFUserEntity user = new DerivedCFUserEntity(); user.PrivClassID = ; user.RefTable = "CF_Employee"; //用到CF_Employee表中的EmployeeID user.RefRecordID = employeeID; user.LoginName = loginName; user.Password = password; user.LanguageSelect = "CN"; user.IsManager = "N"; user.RegionalSetting = "zh-CN"; user.RecordStatus = "Active"; user.CreateUserID = ; user.CreateDate = DateTime.Now; user.ModifyUserID = ; user.ModifyDate = DateTime.Now; adapter.SaveEntity(user); adapter.Commit(); return true; } catch { adapter.Rollback(); return false; } finally { adapter.Dispose(); } } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo(); string loginName = "Amdin"; string password = ""; string firstName = "李"; string lastName = "小龙"; string employeeNo = ""; if (orm.Add(loginName, password, firstName, lastName, employeeNo)) {
Alert("Success");
}
else
{
Alert("Fail");
} 、Update操作(多表记录修改) 例: Update CF_User Set RecordStatus='Inactive' Where UserID= Update CF_Employee Set RecordStatus='Inactive' Where EmployeeID= public bool Modify(int userID, int employeeID) {
DataAccessAdapter adapter = new DataAccessAdapter(); adapter.StartTransaction(IsolationLevel.ReadCommitted, ""); try { DerivedCFUserEntity user = new DerivedCFUserEntity(userID); DerivedCFEmployeeEntity employee = new DerivedCFEmployeeEntity(employeeID); if (user.UserID < || employeeID < ) { return false; } else { //更新CF_User的记录 user.IsNew = false; adapter.FetchEntity(user); user.RecordStatus = "Inactive"; adapter.SaveEntity(user); //更新CF_Employee的记录 employee.IsNew = false; adapter.FetchEntity(employee); employee.RecordStatus = "Inactive"; adapter.SaveEntity(employee); adapter.Commit(); return true;
}
}
catch
{
adapter.Rollback(); return false;
} finally { adapter.Dispose(); } } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo(); int userID = ; int employeeID = ; if (orm. Modify(userID,employeeID)) { Alert("Success"); } else {
Alert("Fail");
} 、Delete操作(多表记录删除) 例: Delete From CF_User Where UserID= Delete From CF_Employee Where EmployeeID= public bool Delete(int userID, int employeeID) {
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.StartTransaction(IsolationLevel.ReadCommitted, "");
try
{ DerivedCFUserEntity user = new DerivedCFUserEntity(userID); DerivedCFEmployeeEntity employee = new DerivedCFEmployeeEntity(employeeID); if (user.UserID < || employeeID < )
{
return false;
}
else
{
//删除CF_User中的记录 adapter.FetchEntity(user); adapter.DeleteEntity(user); //删除CF_Employee中的记录 adapter.FetchEntity(employee); adapter.DeleteEntity(employee); adapter.Commit(); return true;
}
}
catch
{
adapter.Rollback();
return false;
}
finally
{
adapter.Dispose();
} } 对生成代码的调用e.g ORM_Demo orm = new ORM_Demo(); int userID = ; int employeeID = ; if (orm.Delete(userID,employeeID))
{
Alert("Success");
}
else
{
Alert("Fail");
} 示例二: 、
CustomerEntity customer = new CustomerEntity();定义一个空新实体
CustomerEntity customer = new CustomerEntity("SOLDES");定义一个主键值为"SOLDES"的新实体 、
DataAccessAdapter adapter = new DataAccessAdapter();
CustomerEntity customer = new CustomerEntity("CHOPS");
adapter.FetchEntity(customer);
return customer; 直接从数据库中取一条主键为"CHOPS"的记录。它不会存在cache中。
相当于SQL: select * from customers where customerID='CHOPS'
根据主键来返回一条记录 、
DataAccessAdapter adapter = new DataAccessAdapter(true);
OrderEntity order = new OrderEntity();
adapter.FetchEntity(order); order.Customer = (CustomerEntity)adapter.FetchNewEntity(new CustomerEntityFactory(),order.GetRelationInfoCustomer());
adapter.CloseConnection(); 相当于SQL: Select * from customers where CustomerID= (select CustomerID from orders where OrderID=)
在这里,order为customer的子表,先从order表中取一条OrderID=10254的记录,然后再取与这一条记录相关联的Customer的记录。 、
DataAccessAdapter adapter = new DataAccessAdapter();
CustomerEntity customer = new CustomerEntity();
customer.CompanyName = "Chop-suey Chinese";
adapter.FetchEntityUsingUniqueConstraint(customer, customer.ConstructFilterForUCCompanyName()); 相当于SQL: select * from customerS where CompanyName ='Chop-suey Chinese'但是这里CompanyName必须也是唯一的 、
CustomerEntity customer = new CustomerEntity("CHOPS");
DataAccessAdapter adapter = new DataAccessAdapter(true);
adapter.FetchEntity(customer);
customer.Phone = "(605)555-4321";
adapter.SaveEntity(customer);
adapter.CloseConnection(); 相当于SQL: update customerS set phone='(605)555-4321' where customerID='Chop-suey Chinese'
//更新一条记录的一个字段 、
RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.PredicateExpression.Add(ProductFields.CategoryId == ); ProductEntity updateValuesProduct = new ProductEntity();
updateValuesProduct.Discontinued=true;
DataAccessAdapter adapter = new DataAccessAdapter();
int amountUpdated =adapter.UpdateEntitiesDirectly(updateValuesProduct, bucket); 相当于SQL: update products set Discontinued= where CategoryId =
更新CategoryId = 3的所有记录 、
PrefetchPath2 path = new PrefetchPath2((int)EntityType.OrderEntity);
path.Add(OrderEntity.PrefetchPathCustomer); OrderEntity myOrder = new OrderEntity();
adapter.FetchEntity(myOrder, path); myOrder.CustomerID = null;
adapter.save(myOrder); 相当于SQL: Update Orders set CustomerID=NULL where OrderID= 、DataAccessAdapter adapter = new DataAccessAdapter(true);
CustomerEntity customer = new CustomerEntity("CHOPS"); adapter.DeleteEntity(customer); adapter.CloseConnection(); 相当于SQL: Delete customers where customerID='CHOPS' 、
OrderEntity order = new OrderEntity(); DataAccessAdapter adapter = new DataAccessAdapter(); adapter.FetchEntity(order); order.SetNewFieldValue((int)OrderFieldIndex.ShippingDate, null); adapter.SaveEntity(order); 相当于SQL: Update Orders Set ShippedDate=null Where OrderID=
这种写法将不会执行数据验证,使用时要注意这个问题!
也可以这样写: OrderEntity order = new OrderEntity();
DataAccessAdapter adapter = new DataAccessAdapter(); adapter.FetchEntity(order); order.ShippingDate = null; adapter.SaveEntity(order); 、CustomerEntity customer = new CustomerEntity("CHOPS");
customer.SetNewFieldValue((int)CustomerFieldIndex.ContactTitle, null); customer.TestCurrentFieldValueForNull(CustomerFieldIndex.ContactTitle); // returns true 检测一个字段值是否为NULL 、CustomerEntity customer = new CustomerEntity("CHOPS");
DataAccessAdapter Adapter = new DataAccessAdapter(); EntityCollection orders = customer.Orders; Adapter.FetchEntityCollection(orders, customer.GetRelationInfoOrders()); 相当于SQL: Select * from Orders where CustomerID='CHOPS' 通过主表的一个主键值查找与这个主键相关联的子表的记录 以下这种办法也可以: CustomerEntity customer = new CustomerEntity("CHOPS");
DataAccessAdapter Adapter = new DataAccessAdapter(); Adapter.FetchEntityCollection(customer.orders, customer.GetRelationInfoOrders()); 、
EntityCollection<CustomerEntity> customers =new EntityCollection<CustomerEntity>(new CustomerEntityFactory());
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchEntityCollection(customers, null); customers.Sort((int)CustomerFieldIndex.CompanyName, ListSortDirection.Descending); 相当于SQL: Select * From Customers Order By CompanyName desc IPredicate filter = (CustomerFields.Country == "UK");
ArrayList indexes = myCustomers.FindMatches(filter); 这样只在前面的myCustomers 中查找Country == "UK"的记录,不会去数据库中查找。 、
EntityCollection<CustomerEntity> customers = new EntityCollection<CustomerEntity>();
PrefetchPath2 path = new PrefetchPath2(EntityType.CustomerEntity);
path.Add(CustomerEntity.PrefetchPathOrders).SubPath.Add(OrderEntity.PrefetchPathEmployees);
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(customers, null, path);
}
这里一共取了三个表的数据,主表为customers及其的子表Orders及Orders的主表Employess。 、using (DataAccessAdapter adapter = new DataAccessAdapter()) { DataTable table = new DataTable(); table.Columns.Add("CustomerId", typeof(string)); table.Columns.Add("CompanyName", typeof(string)); table.Columns.Add("OrderId", typeof(string)); ResultsetFields fields = new ResultsetFields(); fields[] = CustomersFields.CustomerId; fields[] = CustomersFields.CompanyName; fields[] = OrdersFields.OrderId; RelationPredicateBucket filter = new RelationPredicateBucket(CustomersFields.Country == "Germany"); filter.Relations.Add(CustomersEntity.Relations.OrdersEntityUsingCustomerId); IDataReader reader = adapter.FetchDataReader(fields, filter, CommandBehavior.CloseConnection, , true); while (reader.Read()) { table.Rows.Add(reader.GetValue().ToString(), reader.GetValue().ToString(), reader.GetValue().ToString()); } reader.Close(); } 这是同时从两个表中查找记录的办法 相当于SQL: select customers.customerid,customers.CompanyName from customers where customers.Country = 'USA' 、
EntityCollection employees = new EntityCollection(new EmployeesEntityFactory()); IPrefetchPath2 prefetchPath = new PrefetchPath2((int)EntityType.EmployeesEntity); ISortExpression sorter = new SortExpression(); sorter.Add(OrdersFields.OrderDate | SortOperator.Descending); prefetchPath.Add(EmployeesEntity.PrefetchPathOrders, , null, null, sorter); DataAccessAdapter adapter = new DataAccessAdapter(); adapter.FetchEntityCollection(employees,null, prefetchPath); 相当于SQL: select * from employees 假设第一条记录的employeeid= select top * from orders where employeeid= order by orderid desc 、
ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList();
excludedFields.Add(CustomerFields.ContactName); excludedFields.Add(CustomerFields.Country); EntityCollection customers = new EntityCollection(new EmployeesEntityFactory());
SortExpression sorter = new SortExpression(CustomersFields.CustomerId | SortOperator.Descending); using(DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(customers, null, , sorter, null, excludedFields);
} 相当于SQL: Select ContactName,Country from customers order by CustomerId desc CustomersEntity c = new CustomersEntity("CHOPS");
using(DataAccessAdapter adapter = new DataAccessAdapter()) {
adapter.FetchEntity(c, null, null, excludedFields);
} 相当于SQL:
Select ContactName,Country from customers Where CustomerId ='CHOPS' using(DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchExcludedFields(customers, excludedFields);
adapter.FetchExcludedFields(c, excludedFields);
} 也可以这样写 、
ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList();
excludedFields.Add(OrdersFields.OrderDate); PrefetchPath2 path = new PrefetchPath2(EntityType.CustomersEntity);
path.Add(CustomersEntity.PrefetchPathOrders, excludedFields); EntityCollection customers = new EntityCollection(new CustomersEntityFactory());
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(customers, null, , null, path);
} 、 DataAccessAdapter adapter = new DataAccessAdapter(); // 开始一个事务 adapter.StartTransaction(IsolationLevel.ReadCommitted, "TwoUpates");
try
{
CustomersEntity customer = new CustomersEntity("CHOPS");
OrdersEntity order = new OrdersEntity();
adapter.FetchEntity(customer);
adapter.FetchEntity(order);
// 修改字段
customer.Fax = "";
order.Freight = ; // 保存
adapter.SaveEntity(customer);
adapter.SaveEntity(order); // 提交
adapter.Commit();
}
catch
{
//出错回滚
adapter.Rollback();
throw;
}
finally
{
// 销毁
adapter.Dispose();
} 、以下是一个更好的方法 DataAccessAdapter adapter = new DataAccessAdapter();
try
{
adapter.StartTransaction(IsolationLevel.ReadCommitted, "SavepointRollback");
AddressEntity newAddress = new AddressEntity();
adapter.SaveEntity(newAddress, true); adapter.SaveTransaction("SavepointAddress"); CustomersEntity newCustomer = new CustomersEntity();
newCustomer.VisitingAddress = newAddress;
newCustomer.BillingAddress = newAddress;
try
{
adapter.SaveEntity(newCustomer, true);
}
catch (Exception ex)
{
adapter.Rollback("SavepointAddress");
}
adapter.Commit();
}
catch
{
adapter.Rollback();
throw;
}
finally
{
adapter.Dispose();
} 、
IRelationPredicateBucket filter = new RelationPredicateBucket();
filter.PredicateExpression.Add(CustomersFields.Country == "France");
filter.Relations.Add(OrdersEntity.Relations.CustomersEntityUsingCustomerId);
DataAccessAdapter adapter = new DataAccessAdapter();
int amount = (int)adapter.GetDbCount(new
OrdersEntityFactory().CreateFields(), filter, null, false); 相当于SQL: Select count (*) from orders,customers Where Country = 'France' and customers.customerID=ORDERS.customerID 、protected override void SerializeOwnedData(SerializationWriter writer, object context)
{
base.SerializeOwnedData(writer, context);
writer.WriteOptimized(this.OrderId);
} protected override void DeserializeOwnedData(SerializationReader reader,object context)
{
base.DeserializeOwnedData(reader, context);
this.OrderId = reader.ReadOptimizedInt32();
} 、
PredicateExpression filter = new PredicateExpression(); filter.Add(new FieldBetweenPredicate(OrdersFields.OrderDate,null, new DateTime(, , ), new DateTime(, , ))); RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.PredicateExpression.Add(filter);
EntityCollection customers = new EntityCollection(new OrdersEntityFactory());
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(customers, bucket);
} 相当于SQL: Select * from orders where orderdate between '1996-08-01' and '1996-08-12' 、
EntityCollection Orders= new EntityCollection(new OrdersEntityFactory()); RelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.PredicateExpression.Add(OrdersFields.ShippedDate==System.DBNull.Value); using (DataAccessAdapter adapter = new DataAccessAdapter()) { adapter.FetchEntityCollection(Orders, bucket); } 相当于SQL: select * from orders where shippeddate is null 也可以这样写: bucket.PredicateExpression.Add(new FieldCompareNullPredicate(OrdersFields.ShippedDate,null ,false)); 、
EntityCollection customers = new EntityCollection(new OrdersEntityFactory()); RelationPredicateBucket bucket = new RelationPredicateBucket(); DateTime[] values = new DateTime[] { new DateTime(,,), new DateTime(,,), new DateTime(,,)}; bucket.PredicateExpression.Add(new FieldCompareRangePredicate(OrdersFields.OrderDate,null, values)); using (DataAccessAdapter adapter = new DataAccessAdapter()) { adapter.FetchEntityCollection(customers, bucket); } 相当于SQL: select * from orders where OrderDate in ('1998-04-08' ,'1998-04-13','1998-04-21') 也可以这样写: bucket.PredicateExpression.Add(OrderFields.OrderDate == values);//里面是数组 、
EntityCollection customers = new EntityCollection(new CustomersEntityFactory()); RelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.Relations.Add(CustomersEntity.Relations.OrdersEntityUsingCustomerId); bucket.PredicateExpression.Add(new FieldCompareSetPredicate( CustomersFields.CustomerId,null, OrdersFields.CustomerId,null, SetOperator.In, (OrdersFields.EmployeeId == ))); using (DataAccessAdapter adapter = new DataAccessAdapter()) { adapter.FetchEntityCollection(customers, bucket); } 相当于SQL: select * from customers where Customers.CustomerID IN (SELECT CustomerID FROM Orders WHERE Employeeid=) 、
EntityCollection customers = new EntityCollection(new CustomersEntityFactory()); RelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.PredicateExpression.Add(new FieldLikePredicate (CustomersFields.CompanyName ,null, "%n")); using (DataAccessAdapter adapter = new DataAccessAdapter()) { adapter.FetchEntityCollection(customers, bucket); } 相当于SQL: select * from customers where companyname like '%n' 也可以这样写: bucket.PredicateExpression.Add(CustomersFields.CompanyName % "%n"); 、
ResultsetFields fields = new ResultsetFields();
fields.DefineField(CustomersFieldIndex.Country, , "Country");
fields.DefineField(CustomersFieldIndex.CustomerId, , "AmountCustomers");
fields[].AggregateFunctionToApply = AggregateFunction.CountDistinct;
DataAccessAdapter adp = new DataAccessAdapter();
DataTable table = new DataTable();
IGroupByCollection groupByClause = new GroupByCollection(); groupByClause.Add(fields[]);
groupByClause.Add(fields[]);
adp.FetchTypedList(fields, table, null, , null, false, groupByClause); 、
DataAccessAdapter adapter = new DataAccessAdapter();
decimal orderPrice = (decimal)adapter.GetScalar(OrderDetailsFields.OrderId,(OrderDetailsFields.Quantity * OrderDetailsFields.UnitPrice), AggregateFunction.Sum, (OrderDetailsFields.OrderId == )); 相当于SQL:
select sum(unitprice*quantity) from [Order Details] where orderid= 、
ResultsetFields fields = new ResultsetFields();
fields.DefineField(OrderDetailsFields.OrderId, );
fields.DefineField(OrderDetailsFields.ProductId, );
fields.DefineField(new EntityField2("RowTotal",(OrderDetailsFields.UnitPrice * OrderDetailsFields.Quantity)), ); DataTable results = new DataTable();
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchTypedList(fields, results, null); 相当于SQL: SELECT OrderID,ProductID,(UnitPrice * Quantity) AS RowTotal FROm [Order Details] 、
ResultsetFields fields = new ResultsetFields();
fields.DefineField(CustomersFields.CustomerId, );
fields.DefineField(new EntityField2("NumberOfOrders", new ScalarQueryExpression(OrdersFields.OrderId.SetAggregateFunction(AggregateFunction.Count),(CustomersFields.CustomerId == OrdersFields.CustomerId))), );
DataTable results = new DataTable();
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchTypedList(fields, results, null); 相当于SQL: SELECT CustomerID,(SELECT COUNT(*) FROM Orders WHERE CustomerID = Customers.CustomerID) AS NumberOfOrders FROM Customers

Net框架下-ORM框架LLBLGen的简介的更多相关文章

  1. Net框架下-ORM框架LLBLGen的简介(转载)

    Net框架下-ORM框架LLBLGen的简介 http://www.cnblogs.com/huashanlin/archive/2015/02/12/4288522.html 官方网址:http:/ ...

  2. Java回顾之ORM框架

    这篇文章里,我们主要讨论ORM框架,以及在使用上和JDBC的区别. 概述 ORM框架不是一个新话题,它已经流传了很多年.它的优点在于提供了概念性的.易于理解的数据模型,将数据库中的表和内存中的对象建立 ...

  3. Django(三) 模型:ORM框架、定义模型类并创建一个对应的数据库、配置Mysql数据库

    一.模型概述 https://docs.djangoproject.com/zh-hans/3.0/intro/tutorial02/ https://www.runoob.com/django/dj ...

  4. 【EF 4】ORM框架及其流行产品之一EF介绍

    导读:跳进了多租户切换数据库的坑,那么就继续走下去吧.在我们的项目中,是运用EF实现对数据库的操作,那么EF其实是.NET系统中,基于ORM框架的一个产品实现.在java那边,则有Hibernate和 ...

  5. 轻量级ORM框架 QX_Frame.Bantina(一、框架简介)

    轻量级ORM框架QX_Frame.Bantina系列讲解(开源) 一.框架简介 http://www.cnblogs.com/qixiaoyizhan/p/7417467.html 二.框架使用方式介 ...

  6. Net Core下多种ORM框架特性及性能对比

    在.NET Framework下有许多ORM框架,最著名的无外乎是Entity Framework,它拥有悠久的历史以及便捷的语法,在占有率上一路领先.但随着Dapper的出现,它的地位受到了威胁,本 ...

  7. ORM框架之------Dapper,Net下无敌的ORM

    一,介绍:Dapper是一款轻量级ORM工具.如果你在小的项目中,使用Entity Framework.NHibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀.你又觉得ORM省时省力,这 ...

  8. python(十二)下:ORM框架SQLAlchemy使用学习

    此出处:http://blog.csdn.net/fgf00/article/details/52949973 本节内容 ORM介绍 sqlalchemy安装 sqlalchemy基本使用 多外键关联 ...

  9. ORM 框架简介

    对象-关系映射(Object/Relation Mapping,简称ORM),是随着面向对象的软件开发方法发展而产生的.面向对象的开发方法是当今企业级应用开发环境中的主流开发方法,关系数据库是企业级应 ...

随机推荐

  1. ceph placement group状态总结

    一.归置组状态 1. Creating 创建存储池时,它会创建指定数量的归置组.ceph 在创建一或多个归置组时会显示 creating;创建完后,在其归置组的 Acting Set 里的 OSD 将 ...

  2. Nginx代理与负载均衡配置与优化

    Nginx代理 Nginx从0.7.48版本开始,支持了类似Squid的缓存功能.Nginx的Web缓存服务主要由proxy_cache相关指令集和fastcgi_cache相关指令集构成,前者用于反 ...

  3. 用Photoshop处理图片使背景透明

    用Photoshop处理图片使背景透明 打开一张图片 双击背景或者右键背景图层,新建一个图层, 选择魔棒工具,单击图片, 会自动选择颜色相近的范围 按下键盘的delete键,就可以删除魔棒所选择的区域 ...

  4. SQL Server 性能优化之——T-SQL NOT IN 和 NOT Exists

    这次介绍一下T-SQL中“Not IN” 和“Not Exists”的优化. Not IN 和 Not Exists 命令 : 有些情况下,需要select/update/delete 操作孤立数据. ...

  5. Jstat在分析java的内存GC时的应用

    jstat工具特别强大,有众多的可选项,详细查看堆内各个部分的使用量,以及加载类的数量.使用时,需加上查看进程的进程id,和所选参数. 执行:cd $JAVA_HOME/bin中执行jstat,注意j ...

  6. 浅谈压缩感知(二十五):压缩感知重构算法之分段正交匹配追踪(StOMP)

    主要内容: StOMP的算法流程 StOMP的MATLAB实现 一维信号的实验与结果 门限参数Ts.测量数M与重构成功概率关系的实验与结果 一.StOMP的算法流程 分段正交匹配追踪(Stagewis ...

  7. Linux-vmware tools安装与cdrom挂载

    前述 昨天想直接复制虚拟机centos系统中命令行的内容到主机的txt文档上进行保存,发现不能实现虚拟机与主机之间的直接通讯,后来查资料发现原来是由于我的虚拟机没有安装vwmare tools的缘故. ...

  8. 01_JavaScript简介

    js用途 前端三层 结构层 HTML 从主义角度描述页面的结构 样式层 CSS 从审美的角度装饰页面 行为层 JS 从交互角度提升体验 HTML 里面的 b(加粗)/i(倾斜)/u(下划线)等标签由于 ...

  9. Sublime Text 常用快捷键和优秀插件

    SublimeText3常用快捷键和优秀插件 SublimeText是前端的一个神器,以其精简和可DIY而让广大fans疯狂.好吧不吹了直入正题 -_-!! 首先是安装,如果你有什么软件管家的话搜一下 ...

  10. 文件上传小技巧/原生态【html篇】

    引语:大家都知道,html中上传文件就一个input,type=file就搞定了.但是,这个标签的样式,实在不值得提点什么,要改动他的样式,恐怕也是较难的.但是其实挺简单,今天就来说说上传文件小技巧吧 ...