I am trying to select fields from two tables using the Join clause with LINQ, but l am getting this error:
System.InvalidCastException: ‘Unable to cast object of type ‘<>f__AnonymousType2
13[System.Int32,System.Nullable
1[System.Int32],System.String,System.String,,System.Nullable1[System.DateTime],System.Nullable
1[System.Int32],System.Nullable1[System.Decimal],System.Nullable
1[System.DateTime],System.Nullable1[System.Decimal],System.Nullable
1[System.Decimal]]’ to type ‘ProjectA.Models.Planting’.’
Planting table
CropID | CropName | PlantDate | PlantQty | SiteID |
---|---|---|---|---|
03 | Broccoli | 22/05/2017 | 100 | PlotA |
02 | Mango | 08/06/2017 | 20 | PlotD |
06 | Apple | 02/07/2018 | 20 | PlotF |
Harvest table
Id | CropName | HarvestDate | Weight | CropID |
---|---|---|---|---|
1 | Broccoli | 05/05/2024 | 2.00 | 03 |
2 | Mango | 07/05/2024 | 10.00 | 02 |
3 | Apple | 10/05/2024 | 4.00 | 06 |
The codes below is what l had tried;
<code>public class PlantingController : Controller
{
private readonly dbContext _context;
public PlantingController(dbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult UrlDatasource([FromBody] DataManagerRequest dm)
{
IEnumerable DataSource = (from u in _context.Planting join c in _context.Harvest on u.CropID equals c.CropID
select new { u.CropID, u.CropName, u.PlantDate, u.PlantQty
c.HarvestDate, c.HarvestQty, c.Weight });
return dm.RequiresCounts ? Json(new { result = DataSource}) : Json(DataSource);
}
}
</code>
<code>public class PlantingController : Controller
{
private readonly dbContext _context;
public PlantingController(dbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult UrlDatasource([FromBody] DataManagerRequest dm)
{
IEnumerable DataSource = (from u in _context.Planting join c in _context.Harvest on u.CropID equals c.CropID
select new { u.CropID, u.CropName, u.PlantDate, u.PlantQty
c.HarvestDate, c.HarvestQty, c.Weight });
return dm.RequiresCounts ? Json(new { result = DataSource}) : Json(DataSource);
}
}
</code>
public class PlantingController : Controller
{
private readonly dbContext _context;
public PlantingController(dbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult UrlDatasource([FromBody] DataManagerRequest dm)
{
IEnumerable DataSource = (from u in _context.Planting join c in _context.Harvest on u.CropID equals c.CropID
select new { u.CropID, u.CropName, u.PlantDate, u.PlantQty
c.HarvestDate, c.HarvestQty, c.Weight });
return dm.RequiresCounts ? Json(new { result = DataSource}) : Json(DataSource);
}
}
Expected output
CropID | CropName | PlantDate | PlantQty | HarvestDate | Weight |
---|---|---|---|---|---|
03 | Broccoli | 22/05/2017 | 100 | 05/05/2017 | 2.0 |
02 | Mango | 08/06/2017 | 20 | 07/05/2017 | 10.0 |
06 | Apple | 02/07/2018 | 20 | 10/05/2017 | 4.0 |