-4

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
Jiddo
  • 23
  • 3
  • Perhaps my [SQL to LINQ Recipe](https://stackoverflow.com/questions/49245160/sql-to-linq-with-multiple-join-count-and-left-join/49245786#49245786) might help you. – NetMage Mar 10 '23 at 21:27

3 Answers3

1

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, ..)

EeKay
  • 6,494
  • 3
  • 24
  • 24
0

See if this works

context.Cards.Where(q => q.UserAnalyses.Any()).Select(q => q.CardValue).Distinct().ToList()
vander
  • 138
  • 6
0

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

Felix
  • 9,248
  • 10
  • 57
  • 89