3
votes

I am using nhibernate 3 and fluent nhibernate

I have this enum

[Flags]
public enum Permission
{
    View = 1,
    Add = 2,
    Edit = 4,
    Delete = 8,
    All = View | Add | Edit | Delete
}

Now say I want to find all users that have "view" or "all".

How could I do this with nhibernate(linq)?

session.Query<TableA>().Where x.Permission == Permission.View); // does not bring back all

session.Query<TableA>().Where x.Permission.HasFlag(Permission.View); // crashes

Is there away to do this with having to go

   session.Query<TableA>().Where x.Permission == Permission.View || x.Permission == Permission.All);

Edit

   public class TableAMap : ClassMap<TableA>
    {
        public TableAMap()
        {
            Id(x => x.Id).GeneratedBy.GuidComb();
            Map(x => x.Permission).Not.Nullable().CustomType<PermissionTypes>();
        }
    }
1
Could you show your mapping? Your second example should work, we do this all the time. - kay.herzam
How is your enum saved in the database? As number or string? - cremor
@kay.herzam - I get a System.NotSupportedException was unhandled by user code Message=Boolean HasFlag(System.Enum) Source=NHibernate exception when I do it. - chobo2
please see the edits in my answer - kay.herzam
Can you think of a way to write this query in SQL yourself without having to check for "permission_column = 1 or permission_column = 15"? If not, it's most likely also not possible with NHibernate since NHibernate has to generate a SQL query from your code. - cremor

1 Answers

1
votes

If you have the following mapping for your TableA type:

public class TableAMap : ClassMap<TableA>
{
    public TableAMap()
    {
        ...
        Map(x => x.Permission).CustomType(typeof(Permission)).Not.Nullable();
        ...
    } 
}

Then you should be able to issue the following query in your repository or wherever you do your data ccess:

public IList<TableA> GetTableByPermission(Permission permission)
{
    return Session.Query<TableA>
                  .Where(x => x.Permission == permission ||
                              x.Permission == Permission.All)
                  .ToList();
}

Or you can check whether a single TableA instance has got the required permission:

public bool HasPermission(Guid guid, Permission permission)
{
    var tableA = Session.Query<TableA>.SingleOrDefault(x => x.Id == guid);

    if (tableA != null)
        return (tableA.Permission & permission) == permission;

    // Return false or whatever is appropriate.
    return false;
}

You cannot use your HasFlag() method in the query, NHibernate does not understand how to use that in the query.