具有枚举属性的Nhibernate查询实体

时间:2017-06-07 07:45:59

标签: c# hibernate nhibernate

我需要使用枚举属性Person

查询实体TargetBookingSystemType
public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual TargetBookingSystemType TargetBookingSystemType { get; set; }
}


 public class PersonMap : ClassMap<Person>
 {
     public PersonMap()
     {
        this.CompositeId(x => x.Id).KeyProperty(y => y.AccountName, "[AccountName]").KeyProperty(y => y.Domain, "[Domain]");
        this.Table("Person");
        this.Map(x => x.Key).Column("[Key]");
        this.Map(x => x.TargetBookingSystemType).Column("[TargetBookingSystemType]");//.CustomType<TargetBookingSystemType>();
     }
 }

public enum TargetBookingSystemType
    {
        GoogleCalendarAPIv3 = 1,
        MSExchange2007 = 2,
        MSExchange2010 = 3,
        MSExchange2013 = 4,
        MSOnline = 5
    }

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [nvarchar](20) NULL
 )

我知道一个可能的解决方案是将属性的类型更改为字符串但是如何使用NHibernate实现该属性我可以将属性作为枚举并仍然获得成功的查询?

尝试过CustomType(),但没有遇到错误Input string was not in a correct format.

请注意,当我使用TargetBookingSystemType

的映射注释掉该行时,查询正常

修改

我想对DB进行一次调用,之后根据枚举过滤结果。 这是使用NHibernate进行查询的方法:

public IList<Domain.DomainObjects.Entities.Person> GetAllPersons()
        {
            IList<Domain.DomainObjects.Entities.Person> list = new List<Domain.DomainObjects.Entities.Person>();
            string queryString = "select MR from Person MR";
            return this.Session.CreateQuery(queryString).SetCacheable(true).SetCacheRegion("LongTerm").List<Domain.DomainObjects.Entities.Person>();
        }

如何在结果中获取枚举属性?

2 个答案:

答案 0 :(得分:2)

我没有认为NH required处理 select `posts`.`post_customer_fs_id` AS `post_customer_fs_id`,count(`post_id`) AS `open_post_count`, CASE count(`post_id`) WHEN count(`post_id`)=1 THEN 'A' WHEN count(`post_id`)>1 THEN 'B' END AS AAA from `posts` where (`posts`.`post_status` = '3') AND posts.post_type_id='1' group by `posts`.`post_customer_fs_id` ; 类型有什么特别之处?()?

一旦列的基础数据类型正常(基于@ Jehof的评论),我希望此查询足够:

enum

答案 1 :(得分:0)

当您需要在DB中使用枚举属性和nvarchar列查询实体时,没有解决方案。

可能的解决方法

将属性的数据类型从枚举更改为字符串,并将nvarchar保留在DB中。

public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual string TargetBookingSystemType { get; set; }
}

OR

将enum属性保留在枚举中,但是根据建议将列类型从nvarchar更改为int。您还需要在映射类或xml中指定CustomProperty<enumType>()

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [int] NULL )