Stix Stix - 1 month ago 8
C# Question

Query with LINQ where Context matches multiple parameters from a List of Objects

Presumed I have a table "Article" with multiple columns, e.g.:

CREATE TABLE dbo.Article (
Id int NOT NULL,
ProducerId INT NOT NULL,
Barcode nvarchar(50) NOT NULL,
DescriptionText nvarchar(50) NOT NULL,
ActiveFlag BIT NOT NULL
)


In my ASP.NET Core application I am using LINQ to query that table, e.g.:

IQueryable<Article> query = _context.Article
.Where( p => p.Active == true );


That works of course.
Now I am getting some parameter, which is a very simple Object with a List < ArticleQuery > or alternativly a IEnumerable < ArticleQuery >.

ArticleQuery.cs:

public class ArticleQuery
{
[Required]
public IEnumerable<ArticleRequest> Parts { get; set; }
}

public class ArticleRequest
{
public int ProducerId { get; set; }
public string Barcode { get; set; }
}


Actually I have no clue how to integrate that into LINQ. I tried lots of stuff, but in the end I never figured out to get something like this join:

IQueryable<Article> query = _context.Article
.Join(articleQuery.ArticleRequest,
x => new { a = x.Barcode, b = x.Barcode},
y => new { a = y.ProducerId, b = y.ProducerId},
(x, y) => x);


Also this pseudo-code didn't work (but the Join seems to be the better try):

IQueryable<Article> query = _context.Article.Where( p =>
p.Active == true &&
articleQuery.ArticleRequest.ProducerId.Contains(p.ProducerId) &&
articleQuery.ArticleRequest.Barcode.Contains(p.Barcode)
);


Any ideas how that works correctly?

Answer Source