Natalia
Natalia

Reputation: 111

Error in a LINQ query

I have a problem with this query:

var res = from c in db.Client
          where db.TimesheetLine.Select(o => o.ClientId && 
                                             o.TimesheetId == timesheetId)
                                .Contains(c.Id)
          select c;

I have the error message:

Operator '&&' cannot be applied to operands of type 'int?' and 'bool'.

All I wanna do is to select all the clients which are in a timesheetline X

I have the client class and the timesheetline class

public class CLient 
{
    public int Id { get; set; }
    public string ClientName { get; set; }
}

public class TimesheetLine
{
    public int TimesheetLineId { get; set; }
    public int TimesheetId { get; set; }
    public System.DateTime Date { get; set; }
    public double Duration { get; set; }
    public Nullable<int> ClientId { get; set; }
    public Nullable<int> ClientAddressId { get; set; }
    public int ActivityTypeId { get; set; }
    public string Overtime { get; set; }
    public string Description { get; set; }

    public virtual Activity Activity { get; set; }
    public virtual Client Client { get; set; }
    public virtual ClientAddress ClientAddress { get; set; }
    public virtual Timesheet Timesheet { get; set; }
}

Upvotes: 2

Views: 77

Answers (3)

Christos
Christos

Reputation: 53958

You could make a join

var res = from client in db.Client
          join timesheetLine in db.TimesheetLine
          on client.Id equals timesheetLine.ClientId.GetValueOrDefault()
          where timesheetLine.timesheetId == timesheetId
          select client;

The interesting part here is that we want to base our join on the value of a nullable int, timesheetLine.ClientId and an int, client.Id. In order we make it, we use the GetValueOrDefault method that returns the default value of the nullable, when the nullable has not a value. In this case the value that will be returned would be 0. Assuming that there isn't any client with Id the above works. Differently, we have to change it a bit.

Upvotes: 3

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11544

You cannot write conditional statement inside Select. You can use Any instead:

  var res = from c in db.Client
            where db.TimesheetLine.Any(o => o.ClientId == c.Id)
            select c;

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

Try using a different query:

var res = (from ts in db.TimesheetLine
           where ts.TimesheetId == timesheetId)
           select ts.Client).ToList();

Iterate through the TimsheetLine data, picking out the clients associated with a specific timesheet.

You could do a null check just in case:

var res = (from ts in db.TimesheetLine
           where ts.TimesheetId == timesheetId && ts.Client != null)
           select ts.Client).ToList();

Upvotes: 3

Related Questions