Pergunta

I have a requirement wherein I need to display a list of employees and their roles. So if the role of the employee is Accounting, I want to display FirstName and LastName of that employee. Below is my code for it

SearchTemplate RoleTemplate = new SearchTemplate();
           RoleTemplate.Criteria = DetachedCriteria.For(typeof(CompanyRole), "CR");

      RoleTemplate.Criteria.CreateCriteria("User", "User")
        .SetProjection(Projections.ProjectionList()
            .Add((Projections.Conditional
                        (Restrictions.Eq("CR.Role", Role.Accounting),
                              Projections.Property("User.FirstName"), Projections.Property("User.FirstName"))), "Account")
                               .Add((Projections.Conditional
                        (Restrictions.Eq("CR.Role", Role.Manager),
                              Projections.Property("User.FirstName"), Projections.Property("User.FirstName"))), "Manager"));

The company role table has userid as a foreign key to the primary key id of User table. How is it possible to get the Firstname Lastname field in the "Account" and "Manager" strings above. The above code doesn't work and it puts redundant values of names in both the string. Also, I have a LastName field and i want to append that to the FirstName in the both the strings. Can anybody please explain how will I achieve this? Also, in the above query i have used projections.property twice which I know is wrong but I just wanted to give an idea of what I was looking for.

Foi útil?

Solução

does it have to be in the sql statement? Wouldn't it suffice to:

var result = CreateCriteria<User>()
    .CreateAlias("CompanyRole", "cr")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("FirstName"))
        .Add(Projections.Property("LastName"))
        .Add(Projections.Property("cr.Role"))
        )
    .List<object[]>();

foreach (var item in result)
{
    string name = string.Concat(item[0], item[1]);
    Role role = (Role)item[2];

    // do something with name and role
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top