如何使用实体框架中的枚举替换Int属性?

时间:2022-03-29 09:21:32

I have an entity class that has a property with an underlying db column of datatype Int, however in reality I want this property to be an Enum. Is there any way to specify that this property returns an Enum?

我有一个实体类,其属性具有数据类型为Int的基础db列,但实际上我希望此属性为Enum。有没有办法指定此属性返回枚举?

1 个解决方案

#1


10  

Indirectly, like so.

间接地,像这样。

Personally, I leave the storage int public (for example as DbFoo, where the enum property is Foo) - that way I can still write lambdas against the column for execution at the DB, for example:

就个人而言,我将存储int保留为公共(例如,作为DbFoo,其中枚举属性为Foo) - 这样我仍然可以对列执行lambdas以在DB上执行,例如:

where row.DbFoo == SomeConstant

If you don't expose the storage value, you can't do this as cleanly. You could equally leave it internal, and have some methods in the context to do the filtering... here's one I wrote earlier today:

如果您不公开存储值,则不能干净利落地执行此操作。你可以同样把它留在内部,并在上下文中有一些方法来进行过滤......这是我今天早些时候写的一个:

public IOrderedQueryable<User> Administrators
{
    get { return Users.Where(x => x.DbUserType == User.UserTypeAdmin)
             .OrderBy(x => x.Name);
}

where User.UserTypeAdmin is my internal constant. In this case, I couldn't use a discriminated subclass, as it was interfering with ADO.NET Data Services.

User.UserTypeAdmin是我的内部常量。在这种情况下,我无法使用受歧视的子类,因为它干扰了ADO.NET数据服务。

#1


10  

Indirectly, like so.

间接地,像这样。

Personally, I leave the storage int public (for example as DbFoo, where the enum property is Foo) - that way I can still write lambdas against the column for execution at the DB, for example:

就个人而言,我将存储int保留为公共(例如,作为DbFoo,其中枚举属性为Foo) - 这样我仍然可以对列执行lambdas以在DB上执行,例如:

where row.DbFoo == SomeConstant

If you don't expose the storage value, you can't do this as cleanly. You could equally leave it internal, and have some methods in the context to do the filtering... here's one I wrote earlier today:

如果您不公开存储值,则不能干净利落地执行此操作。你可以同样把它留在内部,并在上下文中有一些方法来进行过滤......这是我今天早些时候写的一个:

public IOrderedQueryable<User> Administrators
{
    get { return Users.Where(x => x.DbUserType == User.UserTypeAdmin)
             .OrderBy(x => x.Name);
}

where User.UserTypeAdmin is my internal constant. In this case, I couldn't use a discriminated subclass, as it was interfering with ADO.NET Data Services.

User.UserTypeAdmin是我的内部常量。在这种情况下,我无法使用受歧视的子类,因为它干扰了ADO.NET数据服务。