Hello i have big problem with Subtract at Linq,EF6. I have date where repair should be finieshed. I woluld like to count how many days left.
At ViewModel I have:
public TimeSpan TimeToLeft{get;set;}
At repair controler i do sth like this:
var repairsToDo = from r in db.Repairs
join c in db.Car on r.Car equals c.ID_Car
join m in db.Models on c.ID_Modelu equals m.ID_Modelu
join b in db.Brand on m.ID_Brand equals b.Brand
where r.Data_Zakonczenia>=DateTime.Today
select new RepairsToDo { TimeToLeft=(r.EndDate-DateTime.Today) };
View:
<table class="ShowDataTab">
<tr>
<th>Repair Number</th>
<th>Car</th>
<th>Name</th>
<th>Desc</th>
<th>Time to left</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>@item.FixNumber</td>
<td>@item.Brand@item.Model</td>
<td>@item.FixName</td>
<td>@item.FixDesc</td>
<td>@item.TimeToLeft</td>
</tr>
}
</table>
And i got error like this:
dbarithmeticexpression arguments must have a numeric common type
How can i Fix it?
EDIT1:
Controler:
var today = DateTime.Today;
var repairsToDo = from r in db.Repair
join c in db.Car on r.Car equals c.ID_Car
join m in db.Models on c.ID_Model equals m.ID_Model
join b in db.Brand on m.ID_Brand equals b.ID_Brand
where r.EndTime>=DateTime.Today
select new { ... EndTime=r.EndTime };
var model = repairsToDo.AsEnumerable().Select(raw => new RepairsToDo {... TimeLeft= raw.EndTime- today });
return View(model);
Error:
The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereSelectEnumerableIterator`2[<>f__AnonymousType1a`7[System.Int32,System.String,System.String,System.String,System.String,System.String,System.DateTime],Praca_Inzynierska.Models.RepairsToDo]', but this dictionary requires a model item of type 'System.Linq.IQueryable`1[Praca_Inzynierska.Models.RepairsToDo]'.
enter code here
It's probably simplest to just fetch the data from EF, and then perform the arithmetic locally:
var today = DateTime.Today;
var rawData = from r in db.Repairs
join c in db.Car on r.Car equals c.ID_Car
join m in db.Models on c.ID_Modelu equals m.ID_Modelu
join b in db.Brand on m.ID_Brand equals b.Brand
where r.Data_Zakonczenia >= DateTime.Today
select new { ..., r.EndDate };
var model = rawData.AsEnumerable() // Perform the select locally
.Select(raw => new RepairsToDo {
... // other properties
TimeToLeft = raw.EndDate - today
});
Note that I've fetched DateTime.Today
once, rather than doing it multiple times - that way you'll get a consistent result, even if this query is performed around midnight.
I'd also recommend renaming TimeToLeft
as TimeLeft
or RemainingTime
.
See more on this question at Stackoverflow