Note that there are some explanatory texts on larger screens.

plurals
  1. POstrange linq to nhibernate issue, Invalid cast from 'System.Int32'
    primarykey
    data
    text
    <p>Calling Get in the following code works fine:</p> <pre><code>public class ContractService : IContractService { private readonly IRepository&lt;Contract&gt; repository; public ContractService(IRepository&lt;Contract&gt; repository) { this.repository = repository; } public Contract Get(int contractId) { return repository.Query().Where(x =&gt; x.Id == contractId).FirstOrDefault(); } </code></pre> <p>but when i do this:</p> <pre><code>public class ContractService : CRUDService&lt;Contract&gt;, IContractService { public ContractService(IRepository&lt;Contract&gt; repository) : base(repository) { } } public class CRUDService&lt;TEntity&gt; : ICRUDService&lt;TEntity&gt; where TEntity : IEntity { protected readonly IRepository&lt;TEntity&gt; repository; public CRUDService(IRepository&lt;TEntity&gt; repository) { this.repository = repository; } public TEntity Get(int id) { var entities = this.repository.Query().Where(s =&gt; s.Id == id); return entities.FirstOrDefault(); } </code></pre> <p>"entities" inside the get method throws an exception when you iterate over it:</p> <pre><code>Invalid cast from 'System.Int32' to 'TEntity' (where TEntity is the type name) </code></pre> <p>Anyone got any idea why?</p> <p>Edit: here's what the different expressions look like:</p> <p>In the generic version (top one), it seems to be trying to convert x for some reason, which must be because of the generics :s</p> <pre><code>{value(NHibernate.Linq.Query`1[Contract]).Where(x =&gt; (Convert(x).Id = value(CRUDService`1+&lt;&gt;c__DisplayClass0[Contract]).Id)).FirstOrDefault()} {value(NHibernate.Linq.Query`1[Contract]).Where(x =&gt; (x.Id = value(ContractService+&lt;&gt;c__DisplayClass2).Id)).FirstOrDefault()} </code></pre> <p>(namespaces omitted for clarity)</p> <p>2nd Edit: It seems to be when it tries to convert between IEntity and the instance type (TEntity)</p> <p>here is IEntity:</p> <pre><code>public interface IEntity { int Id { get; } } </code></pre> <p>3rd Edit: it seems to be the Convert(x) that causes the AssociationVisitor to not properly visit the expression tree and convert "Convert(x).Id"</p> <p>4th Edit: And there we go, someones already found the bug <a href="https://nhibernate.jira.com/browse/NHLQ-11" rel="nofollow noreferrer">https://nhibernate.jira.com/browse/NHLQ-11</a>!</p> <p>Thanks</p> <p>Andrew</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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