I want to use linq query in my asp.net project but I could not translate this sql query as linq to c# code I need help.
SELECT DISTINCT(CardValue) FROM `Cards` INNER JOIN `UserAnalyses` ON Cards.Id = UserAnalyses.CardId
I want to use linq query in my asp.net project but I could not translate this sql query as linq to c# code I need help.
SELECT DISTINCT(CardValue) FROM `Cards` INNER JOIN `UserAnalyses` ON Cards.Id = UserAnalyses.CardId
you could do it using LINQ code like this:
var query = (from c in Cards
join ua in UserAnalyses on c.Id equals ua.CardId
select c.CardValue).Distinct();
//Executing the LINQ query
var result = query.ToList();
But in order to get a better grasp at what you're doing, please add some info (are you using Entity Framework, what are the models like, ..)
See if this works
context.Cards.Where(q => q.UserAnalyses.Any()).Select(q => q.CardValue).Distinct().ToList()
First, you should NEVER "convert" SQL to LINQ. You should create a Model
that approximately matches your database structure. You can use dotnet ef dbcontext scaffold
if you have an existing database. This will get you started.
Second, it is not clear from your question what is the relationship between Card
and UserAnalysis
objects (by the way, I used singular intentionally). But let's say, for the sake of argument that One UserAnalysis ==> Many Cards.
Then you will have a Collection<Card> Cards
member variable in UserAnalysis class.
If you have all that, then you will have a simple LINQ statement:
var cards = _context.UserAnalysis.Select(ua => ua.Cards).CardValue.Distinct()
But for more specific - please show your Model classes