2

I was wondering if there is a way that I could make this block code shorter:

if (rdball.Checked ==true)
{
    var query = from u in context.User
    join ur in context.UserRole on u.ID equals r.UserID
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    select new
    {
    u.ID,
    u.Nick,
    u.LastLogin, 
    Role = ur == null ? String.Empty : r.Name
    };
}
else
{
    var query = from u in context.User
    join ur in context.UserRole on u.ID equals r.UserID
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    where sg.GroupID ==  Convert.ToInt32(cmbGroupSearch.SelectedValue)
    select new
    {
    u.ID,
    u.Nick,
    u.LastLogin, 
    Role = ur == null ? String.Empty : r.Name
    };
}

Without EF I normally make a string with the default query and add the last part with the where depending if the radioubutton is checked or not. Like this

if (rdball.Checked ==true)
    query = query + " where sg.GroupID ==" + Convert.ToInt32(cmbGroupSearch.SelectedValue) 
end if

But I dont understand how to do this with EF. And I would not like that 2000 lines of code become 3000 just for repeat querys. Thanks in advance.

  • 1
    I guess you can do something like `where sg.GroupID == Convert.ToInt32(rdball.Checked ? sg.GroupID : cmbGroupSearch.SelectedValue)` – Jaime Macias Sep 30 '16 at 17:13
  • You can separate the `where` part of your query. See this [answer](http://stackoverflow.com/a/11335767/2030565). – Jasen Sep 30 '16 at 17:20

1 Answers1

1

Where takes any boolean expression, so you can do something like this:

var query = from u in context.User
    join ur in context.UserRole on u.ID equals r.UserID
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    where rdball.Checked ? sg.GroupID ==  Convert.ToInt32(cmbGroupSearch.SelectedValue) : true
    select new
    {
        u.ID,
        u.Nick,
        u.LastLogin, 
        Role = ur == null ? String.Empty : r.Name
    };
Gasper
  • 2,752
  • 1
  • 12
  • 16
  • Exactly what I was looking for. Thanks – bondagemaster Sep 30 '16 at 17:57
  • It could be interesting to see how EF converts this query. – bubi Oct 01 '16 at 07:42
  • @bubi You may try to use Database.Log object of your context or try to call `query.ToTraceString()`, see more [here](http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework). – Gasper Oct 03 '16 at 12:19