Support for Nibernate Icriteria Enum (Bitmask)

[Flags]

public enum ShowProductOn : short

{

    HomePage = 1,

    SalesPage = 2,

    NewsLetter = 4

};

Valid values ​​for this listing are:

1 - Home

2 - SalesPage

3 - Home, SalesPage

4 - NewsLetter

5 - Homepage, NewsLetter

6 - SalesPage, NewsLetter

7 - Homepage, SalesPage, NewsLetter

I would like to write criteria that return all products on the main page. Testing it in C # is very simple:

if ((MY_PARAM and ShowProductOn.HomePage) == ShowProductOn.HomePage)

Console.WriteLine("Yes");

in Sql is also very simple:

DECLARE @BitMask int = 3

IF ((@BitMask and 1) = 1)

TO BEGIN

Print('Yes')

END

These are the NH criteria that I wrote to return all products to the home page (must meet 1 | 3 | 5 | 7):

ICriteria criteria = NHibernateSession.CreateCriteria () .Add (Restrictions.Eq ("ShowProductOn", ShowProductOn.HomePage));

"ShowProductOn" = 1, "ShowProductOn" = 3 | 5 | 7.

- ICriteria/HQL, , "ShowProductOn" = 1 | 3 | 5 | 7?

.

+3
2
+3

, , Restrictions.Like :

:

public virtual DaysOfWeek Weekdays {
  get { return (DaysOfWeek)System.Enum.Parse(typeof(DaysOfWeek), _weekdays); }
  set { _weekdays = value.ToString(); }
}
private string _weekdays = "All";

( hbm.xml)

<property name="Weekdays" column="WEEKDAYS" access="field.camelcase-underscore" not-null="false" />

, , :

Restrictions.Like("Weekdays", ConvertToDaysOfWeek(time.DayOfWeek).ToString(), MatchMode.Anywhere);

, .

+1

Source: https://habr.com/ru/post/1712396/


All Articles