Note that there are some explanatory texts on larger screens.

plurals
  1. POLinq query with Contains only works with is IQueryable is in external variable
    primarykey
    data
    text
    <p>I am using Entity Framework with Linq to Entities, trying to select some data from my database. When I create a Linq query that uses the method <code>IQueryable&lt;int&gt;.Contains</code>, it can only filter the data if I use an external variable! Let me show some example.</p> <p>This block of code, <strong>works perfectly</strong>:</p> <pre><code>var volumes = (from v in work.VolumeAdditiveRepository.All where v.AdditivesID == AdditivesID select v.MetricID); var metrics = from m in work.MetricRepository.All where !volumes.Contains(m.ID) select m; </code></pre> <p>If you take a good look, you can see I use the variable <code>volumes</code> inside this snippet, in the <code>where</code> condition. If I copy the contents of this variable and paste it inside the <code>metrics</code> variable, leading to the code below, it raises the error: <code>"Unable to create a constant value of type 'CalculadoraRFS.Models.Domain.VolumeAditivo'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."</code>.</p> <pre><code>var metrics = from m in work.MetricRepository.All where !(from v in work.VolumeAdditiveRepository.All where v.AdditivesID == AdditivesID select v.MetricID).Contains(m.ID) select m; </code></pre> <p>How can I variable substitution cause such error?! Am I doing (certainly) something wrong?<br> Thank you!</p> <hr> <p><strong>UPDATE:</strong></p> <p>Actually, I find out that the Repository Pattern or DbContext seems to be the problem, as @jhamm pointed out. The snippet below doesn't work either:</p> <pre><code>var query = from m in work._context.Metric where !(from v in work._context.VolumeAdditive where v.AdditivesID == AdditivesID select v.MetricID).Contains(m.ID) select m; </code></pre> <p>But the snippet below works. I just took the context out of the UnitOfWork class, though it is very simply defined there: <code>public CalculadoraRFSContext _context = new CalculadoraRFSContext();</code>.</p> <pre><code>var _context = new CalculadoraRFSContext(); var query = from m in _context.Metric where !(from v in _context.VolumeAdditive where v.AdditivesID == AdditivesID select v.MetricID).Contains(m.ID) select m; </code></pre> <p>Now I'm really confused about this stuff! Wasn't it supposed to work as expected?!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload