Reputation: 85785
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>();
}
}
Upvotes: 3
Views: 2313
Reputation: 3063
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.
Upvotes: 1