I have the following code
RoseFlowersData = (from c in dbContext.ClientFirst
where c.RoseFlower.Id == Id
select new FlowerDTO
{
flowerId = c.Id,
flowerCatergory = c.flowerCatergory
}),
AsterFlowerData = (from c in dbContext.ClientFirst
where c.AsterFlower.Id == Id
select new FlowerDTO
{
flowerId = c.Id,
flowerCatergory = c.flowerCatergory
}),
in both, the only difference is the where
clause (where c.RoseFlower.Id == Id; where c.AsterFlower.Id == Id
)
I want to use following function to get me data based on different flower type (like RoseFlower, AsterFlower etc)
private IQueryable<FlowerDTO> GetFlowerData(int flowerId, <What should I pass here?>)
{
var data = (from c in dbContext.ClientFirst
where c.RoseFlower.Id == flowerId
select new FlowerDTO
{
flowerId = c.Id,
flowerCatergory = c.flowerCatergory
});
return data;
}
I am confused on how I can use this function for both and further flower types. I have tried looking for solutions to isolate the where clause but after hours of search, I have not been able to find a solution. Maybe I am not searching for the right thing.
Thank you for your time and help
CodePudding user response:
I agree with @Andrew H, but instead of passing Predicate<Flower> where
as a parameter, I did passing only the Id and FlowerType, just to have less repetitions and better to maintenance:
private IQueryable<FlowerDTO> GetFlowerData(int id, string flowerType)
{
var data = dbContext.ClientFirst
.Where(f => f.Id == Id && f.FlowerType == flowerType)
.Select(c => new FlowerDTO
{
flowerId = c.Id,
flowerCatergory = c.flowerCatergory
});
return data;
}
and then:
GetFlowerData(1, "RoseFlower");
GetFlowerData(2, "AsterFlower");
Just ideas to you create your own function. Have fun.
CodePudding user response:
If you convert your LINQ to a fluid syntax using the LINQ extension methods instead:
private IQueryable<FlowerDTO> GetFlowerData(Predicate<Flower> where)
{
var data = dbContext.ClientFirst
.Where(where)
.Select(c => new FlowerDTO
{
flowerId = c.Id,
flowerCatergory = c.flowerCatergory
});
return data;
}
Then call your method:
GetFlowerData(f => f.Id == desiredFlowerId && f.FlowerType == "RoseFlower");