当前位置:首页 > 开发教程 > ADO.NET >

枚举的使用

时间:2013-09-22 09:34 来源: 作者: 收藏

2345软件教程,为您打造全面的软件教程手册,无论是新奇小软件的操作还是专业软件的使用技巧,2345软件教程都会为您解疑释惑。

核心提示:本文将通过ADO.NET Entity Framework 4中枚举的使用介绍,带领大家走进ADO.NET的世界。

本文将通过ADO.NET Entity Framework 4中枚举的使用介绍,带领大家走进ADO.NET的世界。

枚举(Enum)是一种常用的类型,如用于表示状态、类型等参数。但目前它不会被官方地在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类型。

我们按常规做法写一个用于表示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);


上一篇:技术路线
下一篇:实用技巧两则

ADO.NET阅读排行

最新文章