Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nHibernate, I can tell it to Fetch<T>, but can I tell it to Stay<T>?

Just as the question states, I know that using NHinbernate I can tell a specific query to Fetch(Func<T,bool>), and even FetchMany(). But what if I want to do the other way around?

For instance, let us say that we have a class ..

class Employee {
  public virtual string Name { get; set; }
  public virtual Address Address { get; set; }
  public virtual double Salary { get; set; }
}

If an Employee is looking at their own profile, I would want Address and Salary to be rendered. But what if a different employee is looking? It would seem more convenient to build one ASP.NET MVC View, but to specifically not return the data that needs to be hidden. So like ..

if( // myself // ) {
   return employee = session.Query<Employee>()
       .Fetch(context => context.Address)
       .Take(1)
       .SingleOrDefault();
}
else
   return employee = session.Query<Employee>()
       .Deny(context => context.Address)
       .Deny(context => context.Salary)
       .Take(1)
       .SingleOrDefault();

Then my View might look like ..

@model Employee

<h2>@Model.Name</h2>
<h4>@Html.DisplayFor( model => model.Address )</h4>
<h4>@Model.Salary</h4>

I realize this isn't the best example in the universe, but is such a thing possible? I haven't found any methods that explicitly tell an object not to return, so far.

like image 523
Ciel Avatar asked Nov 28 '25 15:11

Ciel


1 Answers

As always the answer to everything in ASP.NET MVC is : view models. So you fetch everything in your repository and return a domain Employee model containing all properties and then you would map this Employee model to an EmployeeViewModel. It is then this view model that will be passed to the view. And when the controller maps between the model and the view model depending on the user it might include or not some properties.

like image 57
Darin Dimitrov Avatar answered Dec 01 '25 13:12

Darin Dimitrov