C
C#4mo ago
Raki

Is there a way I can improve this code? I feel its kind of hard to understand

c#

var plasticWay = await (from plastic in _context.plasticWays
join assetFrom in _context.Assets on plastic.plasticFrom equals assetFrom.Id
join assetTo in _context.Assets on plastic.plasticTo equals assetTo.Id
join categoryFrom in _context.AssetsCategory on assetFrom.CategoryId equals categoryFrom.Id
join categoryTo in _context.AssetsCategory on assetTo.CategoryId equals categoryTo.Id
where plastic.Id == id
select new plasticWayResponse
{
Id = plastic.Id,
plasticWayFrom = new plasticWayFrom
{
AssetName = assetFrom.AssetName,
AssetCategoryName = categoryFrom.CategoryName
},
plasticWayTo = new plasticWayTo
{
AssetName = assetTo.AssetName,
AssetCategoryName = categoryTo.CategoryName
},
Source = plastic.Source,
AvailableFrom = plastic.AvailableFrom,
AvailableTo = plastic.AvailableTo

}).FirstOrDefaultAsync();
return plasticWay ?? throw new KeyNotFoundException("plasticWayId not found");

c#

var plasticWay = await (from plastic in _context.plasticWays
join assetFrom in _context.Assets on plastic.plasticFrom equals assetFrom.Id
join assetTo in _context.Assets on plastic.plasticTo equals assetTo.Id
join categoryFrom in _context.AssetsCategory on assetFrom.CategoryId equals categoryFrom.Id
join categoryTo in _context.AssetsCategory on assetTo.CategoryId equals categoryTo.Id
where plastic.Id == id
select new plasticWayResponse
{
Id = plastic.Id,
plasticWayFrom = new plasticWayFrom
{
AssetName = assetFrom.AssetName,
AssetCategoryName = categoryFrom.CategoryName
},
plasticWayTo = new plasticWayTo
{
AssetName = assetTo.AssetName,
AssetCategoryName = categoryTo.CategoryName
},
Source = plastic.Source,
AvailableFrom = plastic.AvailableFrom,
AvailableTo = plastic.AvailableTo

}).FirstOrDefaultAsync();
return plasticWay ?? throw new KeyNotFoundException("plasticWayId not found");

2 Replies
Omnissiah
Omnissiah4mo ago
you could use .Include() instead of join, you can move them to a method, but apart from that there's not much you can do
Schreck
Schreck4mo ago
You only can use .Include of you have navigation properties, correct? Anyway, do you need this query in various situations? Linq is Linq, there is nothing much against it. Maybe create a real view on the database, but that is just another facade.
Want results from more Discord servers?
Add your server