Core Concepts > Advanced Queries
Enums
Enums are fully supported in dbExpression with the appropriate scaffold and runtime configuration (see Runtime Configuration).
Using enums in QueryExpressions is like using any other data type. In the sample console application, we have a few enums defined. Let's look at the definition of the AddressType
enum:
public enum AddressType : int
{
[Display(Name = "Shipping", Description = "Shipping Address")]
Shipping = 0,
[Display(Name = "Mailing", Description = "Mailing Address")]
Mailing = 1,
[Display(Name = "Billing", Description = "Billing Address")]
Billing = 2,
}
Let's look at some examples using enums in queries, starting with a few SELECT operations using the AddressType
enum:
IEnumerable<Address> billing_addresses = db.SelectMany<Address>()
.From(dbo.Address)
.Where(dbo.Address.AddressType == AddressType.Billing)
.Execute();
Note that the WHERE clause uses the enum value, not the numeric version of the enum.
An example using an enum with an In
clause:
IEnumerable<Address> billing_and_mailing_addresses = db.SelectMany<Address>()
.From(dbo.Address)
.Where(dbo.Address.AddressType.In(AddressType.Billing, AddressType.Mailing))
.Execute();
In a GroupBy
clause:
IEnumerable<dynamic> count_by_address_type = db.SelectMany(
dbo.Address.AddressType,
db.fx.Count(dbo.Address.Id).As("AddressCount")
)
.From(dbo.Address)
.GroupBy(dbo.Address.AddressType)
.Execute();
In an IsNull
database function:
IEnumerable<AddressType> address_types = db.SelectMany(
db.fx.IsNull(dbo.Address.AddressType, AddressType.Billing)
)
.From(dbo.Address)
.Execute();
Using the AddressType
enum in an UPDATE operation:
db.Update(
dbo.Address.AddressType.Set(AddressType.Mailing)
)
.From(dbo.Address)
.Where(dbo.Address.AddressType == dbex.Null)
.Execute();
Let's look at another enum from the sample console application, PaymentMethodType
:
public enum PaymentMethodType : int
{
[Display(Name = "Credit Card", Description = "Credit Card")]
CreditCard = 1,
[Display(Name = "ACH", Description = "ACH")]
ACH = 2,
[Display(Name = "Pay Pal", Description = "Pay Pal")]
PayPal = 3
}
This enum has been configured (in scaffolding configuration) similar to configuring the AddressType
enum. We have also indicated that we desire to persist the enum using it's string value as detailed in Runtime Configuration. The PaymentMethodType column in the Purchase table has a database type of VARCHAR(20). Using this in a query is exactly the same as those persisted using their numeric value.
IEnumerable<Purchase> credit_card_purchases = db.SelectMany<Purchase>()
.From(dbo.Purchase)
.Where(dbo.Purchase.PaymentMethodType == PaymentMethodType.CreditCard)
.Execute();
Note in the SQL statement that the parameter value (@P1
) used in the WHERE clause is the string value of the PaymentMethodType
enum.