1 如何讀取指定的表的內容到集合中
DataAccessAdapter adapter = new DataAccessAdapter();
EntityCollection allCustomers = new EntityCollection(new CustomerEntityFactory());
adapter.FetchEntityCollection(allCustomers, null);
ProductEntity newProduct = new ProductEntity();
newProduct.CategoryID=1;
newProduct.Discontinued=false;
newProduct.ProductName="TooCool";
newProduct.UnitsOnOrder=0;
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.SaveEntity(newProduct);
1)數據庫已經加載到內存中
CustomerEntity customer = new CustomerEntity("FISSA");
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchEntity(customer);
2)設置實體主鍵,直接從數據庫中刪除
CustomerEntity customer = new CustomerEntity("FISSA");
adapter.DeleteEntity(customer);
3) 使用斷言表達式(predicate expression)直接從數據庫中刪除
IRelationPredicateBucket bucket = new RelationPredicateBucket((CustomerFields.CustomerID == "FISSA"));
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.DeleteEntitiesDirectly("CustomerEntity", bucket);
DataAccessAdapter adapter = new DataAccessAdapter("data source=myServer;initial catalog=Northwind;UID=myUserID;PWD=secret");
CustomerEntity customer = new CustomerEntity("CHOPS"); DataAccessAdapter adapter = new DataAccessAdapter(); bool loadedCorrectly = adapter.FetchEntity(customer);
讀取FetchEntity的返回值,true表示是從數據庫中加載
CustomerEntity customer = new CustomerEntity("CHOPS"); DataAccessAdapter adapter = new DataAccessAdapter(); adapter.FetchEntity(customer); bool loadedCorrectly = (customer.Fields.State == EntityState.Fetched);
查看Fields.State的值,Fetched表示是已經從數據庫中加載
二個方法:查詢實體的屬性PrimaryKeyFields(類型是ArrayList),也可以遍歷對象的屬性,檢查它的IsPrimaryKey的值
不給該字段指定任何值可以保證數據庫的值是NULL,也可以通過指定null來設為NULL
CustomerEntity customer=new CustomerEntity(“CDC”);
customer.ContactTitle=null;
這會導致ContactTitle的數據庫字段值是NULL,這一句也可以不寫,常常會省略
CustomerEntity customer = new CustomerEntity("CHOPS");
customer.SetNewFieldValue((int)CustomerFieldIndex.ContactTitle, null);
也可以這樣寫
CustomerEntity customer = new CustomerEntity("CHOPS");
customer.SetNewFieldValue("ContactTitle", null);
說明:新實體,表示在內存中新創建的,沒有與數據庫發生關聯或沒有保存到數據庫中
已經存在的實體,常常是從為數據庫中讀取記錄值,並填充到實體的屬性值中
OrderEntity newValues = new OrderEntity();
newValues.EmployeeID = 5;
IRelationPredicateBucket filter = new RelationPredicateBucket((OrderFields.EmployeeID == 2)); DataAccessAdapter adapter = new DataAccessAdapter();
adapter.UpdateEntitiesDirectly(newValues, filter);
這幾句,把OrderEntity 中所有EmployeeID 為2的值,都更新為5
SortExpression sorter = (OrderFields.OrderDate | SortOperator.Descending) & (CustomerFields.CompanyName | SortOperator.Ascending);
IPredicateExpression filter = new PredicateExpression();
filter.Add(YourEntityFields.Field == 3);
IPredicateExpression filter = new PredicateExpression();
filter.Add(OrderFields.OrderDate == OrderFields.ShippingDate);
IPredicateExpression filter = new PredicateExpression();
filter.Add(YourEntityFields.Field % "%Foo%");
IPredicateExpression filter = new PredicateExpression();
filter.Add(new FieldBetweenPredicate(YourEntityFields.Field, Null, 1, 10));
IPredicateExpression filter = new PredicateExpression();
int[] values = new int[3] {1, 2, 5};
filter.Add(YourEntityFields.Field == values);
也可以用ArrayList來實現
IPredicateExpression filter = new PredicateExpression();
ArrayList values = new ArrayList();
values.Add(1); values.Add(2); values.Add(5);
filter.Add(YourEntityFields.Field == values);
這種辦法更直接
IPredicateExpression filter = new PredicateExpression();
filter.Add(new FieldCompareRangePredicate(YourEntityFields.Field, Nothing, 1, 2, 5));
IPredicateExpression filter = new PredicateExpression();
filter.Add(new FieldCompareSetPredicate( YourEntityFields.Field, null, FooFields.Fieldb, null, SetOperator.In, null));
IPredicateExpression filter = new PredicateExpression();
filter.Add(YourEntityFields.Field == DBNull.Value));
ResultsetFields fields = new ResultsetFields(3);
fields.DefineField(EmployeeFields.FirstName, 0, "FirstNameManager", "Manager");
fields.DefineField(EmployeeFields.LastName, 1, "LastNameManager", "Manager");
fields.DefineField(EmployeeFields.LastName, 2, "NumberOfEmployees", "Employee", AggregateFunction.Count); IRelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.Relations.Add(EmployeeEntity.Relations.EmployeeEntityUsingEmployeeIdReportsTo, "Employee", "Manager", JoinHint.None);
IGroupByCollection groupByClause = new GroupByCollection();
groupByClause.Add(fields[0]);
groupByClause.Add(fields[1]);
DataAccessAdapter adapter = new DataAccessAdapter();
DataTable tlist = new DataTable();
adapter.FetchTypedList(fields, tlist, bucket, 0, null, true, groupByClause);
EntityView2 view = new EntityView2(customers);
view.Sorter = (new EntityProperty("propertyName") | SortOperator.Ascending);
DataAccessAdapter adapter = new DataAccessAdapter();
int maxValue = (int)adapter.GetScalar(OrderFields.OrderId, (OrderFields.ShippedDate - OrderFields.OrderDate), AggregateFunction.Max, (OrderFields.CustomerId == _customerId));
ResultsetFields fields = new ResultsetFields(2);
fields.DefineField(CustomerFieldIndex.Country, 0, "Country");
fields.DefineField(CustomerFieldIndex.CustomerID, 1, "AmountCustomers");
fields[1].AggregateFunctionToApply = AggregateFunction.CountDistinct;
DataAccessAdapter adapter = new DataAccessAdapter();
decimal orderPrice = (decimal)adapter.GetScalar(OrderDetailsFields.OrderId, (OrderDetailsFields.Quantity * OrderDetailsFields.UnitPrice), AggregateFunction.Sum, (OrderDetailsFIelds.OrderId == 10254));
-- SQL 查詢列RowTotal 是表達式
SELECT OrderID, ProductID, (UnitPrice * Quantity) AS RowTotal
FROM [Order Details]
寫法如下
ResultsetFields fields = new ResultsetFields(3);
fields.DefineField(OrderDetailsFields.OrderID, 0);
fields.DefineField(OrderDetailsFields.ProductID, 1);
fields.DefineField(new EntityField2("RowTotal", (OrderDetailsFields.UnitPrice * OrderDetailsFields.Quantity)), 2);
DataTable results = new DataTable();
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchTypedList(fields, results, null);
Dictionary<string, string> customProperties = CustomerEntity.CustomProperties;
string description = customProperties["Description"];
也可以用CustomPropertiesOfType
Dictionary<string, string> customProperties = customer.CustomPropertiesOfType;
string description = customProperties["Description"];
如果要取特定的自定義屬性而不是全部屬性,可以這樣寫
Dictionary<string, string>fieldCustomProperties = CustomerEntity.FieldsCustomProperties["CustomerID"];
string description = fieldCustomProperties["Description"];
給實體設置驗證類,並重寫ValidateEntityBeforeSave
public override void ValidateEntityBeforeSave( IEntityCore involvedEntity )
{ CustomerEntity toValidate = (CustomerEntity)involvedEntity;
}
protected override bool ValidateFieldValue( IEntityCore involvedEntity, int fieldIndex, object value )
{
bool toReturn = true; switch((OrderFieldIndex)fieldIndex)
{
case OrderFieldIndex.OrderId: // id is valid if the value is > 0
toReturn = ((int)value > 0); break;
default:
toReturn = true; break;
}
return toReturn;
}
int outputValue;
DataTable resultSet = RetrievalProcedures.MyStoredProcedure(1, 2, 3, 4, ref outputValue);
例如,Customer(CustomerNo,Name,Address,Telephone,ContactName,Country), 現在只想寫這樣的查詢
SELECT ContactName,Country FROM Customer,即只查客戶的名稱和所屬的國家
ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList(false);
excludedFields.Add(CustomerFields.ContactName);
excludedFields.Add(CustomerFields.Country);
CustomerCollection customers = new CustomerCollection();
SortExpression sorter = new SortExpression(CustomerFields.CustomerId | SortOperator.Descending); customers.GetMulti(null, 0, sorter, null, null, excludedFields, 0, 0);
這樣,LLBL Gen會產生SQL:SELECT ContactName,Country FROM Customer,而不是查詢所有字段
如果反過來,ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList();
用這一句替換開頭的一句,則是表示不查詢ContactName和Country這兩個字段。
IPredicate filter = (CustomerFields.Country == "UK");
List<int> indexes = myCustomers.FindMatches(filter);
29 如何調用數據庫函數
CREATE FUNCTION fn_CalculateOrderTotal(@orderID int, @useDiscounts bit) RETURNS DECIMAL AS BEGIN …… END
ResultsetFields fields = new ResultsetFields(1);
fields.DefineField( OrderFields.OrderId, 0, "OrderID" );
fields[4].ExpressionToApply = new DbFunctionCall( "dbo", "fn_CalculateOrderTotal", new object[] { OrderFields.OrderId, 1 } );
DataTable results = new DataTable();
using(DataAccessAdapter adapter = new DataAccessAdapter() )
{ adapter.FetchTypedList( fields, results, null ); }
序列化
protected override void OnGetObjectData(SerializationInfo info, StreamingContext context)
{
info.Add("_orderTotal", _orderTotal);
}
反序列化
protected override void OnDeserialized(SerializationInfo info, StreamingContext context)
{
_orderTotal = info.GetDecimal("_orderTotal");
}
數據庫字段屬性默認是序列化,如果給entity加入了自定義屬性,則需要像上面的例子一樣實樣序列化。
IRelationPredicateBucket filter = new RelationPredicateBucket();
filter.PredicateExpression.Add(CustomerFields.Country == "France");
filter.Relations.Add(OrderEntity.Relations.CustomerEntityUsingCustomerId);
DataAccessAdapter adapter = new DataAccessAdapter();
int amount = (int)adapter.GetDbCount(new OrderEntityFactory().CreateFields(), filter, null, false);
小技巧:LLBL Gen已經提供了Debugger Visualizers,在Debug時,可以查看到一段ORM語句的偽SQL,很方便調試問題。請把Frameworks\LLBLGen Pro\RuntimeLibraries\DebuggerVisualizers目錄中的SD.LLBLGen.Pro.DebugVisualizers.dll拷貝到My Documents\Visual Studio xxyy\Visualizers目錄中。