詳解ADO.NET Entity Framework 4中枚舉的使用
本文將通過ADO.NET Entity Framework 4中枚舉的使用介紹,帶領大家走進ADO.NET的世界。
枚舉(Enum)是一種常用的類型,如用于表示狀態(tài)、類型等參數。但目前它不會被官方地在ADO.NET Entity Framework中進行支持。本文介紹的是通過復雜類型(Complex Types)在ADO.NET Entity Framework 4中使用枚舉。
這種方法需要使用POCO類,而不能使用Visual Studio自動生成的類。因為我們需要手動為復雜類型編寫代碼。
數據庫腳本:
- 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)
這是一個用于存放帳號信息的數據表,Role是個枚舉類型,在數據庫中用int類型。
我們按常規(guī)做法寫一個用于表示Role的枚舉類型
- public enum AccountRoleEnum
- {
- Admin = 1,
- User = 2
- }
然后寫一個復雜類型用于在枚舉類型和數據庫的int類型之間做變換。復雜類型只有在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個方法用于隱式類型重載,也就是對類型進行變換。
然后我們寫Account實體。
- 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; }
和實體框架上下文。
- public class EntitiesContext : ObjectContext
- {
- public EntitiesContext()
- : base("name=Entities", "Entities")
- {
- _accounts = CreateObjectSet<Account>();
- }
- public ObjectSet<Account> Accounts
- {
- get
- {
- return _accounts;
- }
- }
- private ObjectSet<Account> _accounts;
- }
這樣,主要的工作就已經完成了,在比較時可以使用
- account.Role == AccountRoleEnum.Admin
但是在涉及到數據庫的查詢時,這樣的寫法是會報錯的,只能使用
- EntitiesContext db = new EntitiesContext();
- db.Accounts.Where(c => c.Role.Value == (int)AccountRoleEnum.Admin);