LINQ to Entities generating incorrect SQL

This is the kind of query that EF generates when it knows for sure that the query won’t return any results. Such a query minimizes database processing.

How can EF be so sure? This can only be when for all it knows UserId in the database is not nullable. This, in turn, can only be when there’s also a User reference in Certificate (the POCO class) that is mapped as required. Look for something like

HasRequired(t => t.User).WithMany(t => t.Certificates)

in an EntityTypeConfiguration<Certificate>, or in an override of OnModelCreating in your DbContext. (In code-first it is possible to have a required reference, while the accompanying primitive Id property is a nullable type. In an edmx file this doesn’t validate).

So I think you have to map User as optional if in the database the foreign key is nullable.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)