本文將通過(guò)ADO.NET Entity Framework 4中枚舉的使用介紹,帶領(lǐng)大家走進(jìn)ADO.NET的世界。
枚舉(Enum)是一種常用的類(lèi)型,如用于表示狀態(tài)、類(lèi)型等參數(shù)。但目前它不會(huì)被官方地在ADO.NET Entity Framework中進(jìn)行支持。本文介紹的是通過(guò)復(fù)雜類(lèi)型(Complex Types)在ADO.NET Entity Framework 4中使用枚舉。
這種方法需要使用POCO類(lèi),而不能使用Visual Studio自動(dòng)生成的類(lèi)。因?yàn)槲覀冃枰謩?dòng)為復(fù)雜類(lèi)型編寫(xiě)代碼。
數(shù)據(jù)庫(kù)腳本:
if exists (select 1
from sysobjects
where id = object_id('Account')
and type = 'U')
drop table Account go create table Account
(
ID uniqueidentifier not null default NewSequentialID(),
UserName nvarchar(20) not null,
Password varchar(40) not null,
Email nvarchar(100) not null,
Role int not null,
constraint PK_ACCOUNT primary key (ID)
)
insert into Account (UserName ,Password,Email ,Role ) values ('Test1','Test1','test1',1)
insert into Account (UserName ,Password,Email ,Role ) values ('Test2','Test2','test2',1)
insert into Account (UserName ,Password,Email ,Role ) values ('Test3','Test3','test3',2)
這是一個(gè)用于存放帳號(hào)信息的數(shù)據(jù)表,Role是個(gè)枚舉類(lèi)型,在數(shù)據(jù)庫(kù)中用int類(lèi)型。
我們按常規(guī)做法寫(xiě)一個(gè)用于表示Role的枚舉類(lèi)型
public enum AccountRoleEnum {
Admin = 1,
User = 2
}
然后寫(xiě)一個(gè)復(fù)雜類(lèi)型用于在枚舉類(lèi)型和數(shù)據(jù)庫(kù)的int類(lèi)型之間做變換。復(fù)雜類(lèi)型只有在ADO.NET Entity Framework 4中才有。
public partial class RoleWrapper
{
private AccountRoleEnum m_orderStatus;
public int Value
{
get {
return (int)m_orderStatus;
}
set {
m_orderStatus = (AccountRoleEnum)value;
} }
public AccountRoleEnum EnumValue
{
get {
return m_orderStatus;
}
set {
m_orderStatus = value;
}
}
public static implicit operator RoleWrapper(AccountRoleEnum role)
{
return new RoleWrapper {
EnumValue = role
};
}
public static implicit operator AccountRoleEnum(RoleWrapper role)
{
if (role == null)
return AccountRoleEnum.User;
return role.EnumValue;
}
} 最后的2個(gè)方法用于隱式類(lèi)型重載,也就是對(duì)類(lèi)型進(jìn)行變換。
然后我們寫(xiě)Account實(shí)體。
public class Account
{
public Guid ID
{
get;
set;
}
public string UserName { get; set;
}
public string Password
{
get;
set;
}
public string Email
{
get;
set;
}
public RoleWrapper Role
{
get;
set;
} 和實(shí)體框架上下文。
public class EntitiesContext : ObjectContext
{
public EntitiesContext()
: base("name=Entities", "Entities")
{
_accounts = CreateObjectSet();
}
public ObjectSet Accounts
{
get
{
return _accounts;
}
}
private ObjectSet _accounts;
}
這樣,主要的工作就已經(jīng)完成了,在比較時(shí)可以使用
account.Role == AccountRoleEnum.Admin 但是在涉及到數(shù)據(jù)庫(kù)的查詢(xún)時(shí),這樣的寫(xiě)法是會(huì)報(bào)錯(cuò)的,只能使用
EntitiesContext db = new EntitiesContext(); db.Accounts.Where(c => c.Role.Value == (int)AccountRoleEnum.Admin);
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄