We’re using both Entity Framework and OData.
Our entity classes have the [PrimaryKey] annotation but also the individual properties in the primary key have the [Key] annotation. Sonar doesn’t like this and reports that the [Key] attributes should be replaced with [PrimaryKey] attribute or the HasKey fluent API.
The [PrimaryKey] is used during the database context’s model building, which uses Microsoft.EntityFrameworkCore.ModelBuilder but it is ignored by Odata.
The [Key] attribute, while it can be used by the EF model builder, is also used by the ODataConventionModelBuilder.
While both [PrimaryKey] and [Key] annotations can be replaced by HasKey Fluent API method (different methods for the 2 builders) for the entity, we prefer to use annotations and, as far as I can see, the [Key] attribute is the only attribute option I can find that stops AddOData throwing an error.
The downside compared to the Fluent API method is that is that it doesn’t have any ability to specify order of the keys.
Is there some Sonar approved way of using attributes for a composite primary key that is used by the ODataConventionModelBuilder?
Hi @Chris-Huzza,
Yes, this seems to be a false positive in your scenario. Rule S8717 was written exclusively for EF Core and has no awareness of ODataConventionModelBuilder. In pure EF Core, multiple [Key] attributes on a composite key don’t work (EF Core ignores the extras and treats them as single-column keys), which is why the rule recommends [PrimaryKey] or the fluent API. But [Key] is what ODataConventionModelBuilder requires, so in your mixed EF + OData stack, keeping both annotations is the correct approach.
There is no “Sonar-approved” attribute combination that satisfies both builders simultaneously today, the rule doesn’t know about OData.
Your best options:
- Mark the issues as Won’t Fix in the SonarQube UI — this documents the intentional decision without touching your source code.
- Disable S8717 from your quality profile if this pattern is pervasive across your project.
I’ll flag this internally as a potential improvement, the rule could be extended to recognise that [Key] is also used by OData conventions and avoid flagging the combination in that context.
Best regards,
Stevan
Morning Stevan,
cheers for the quick response and confirmation there isn’t a way to use an annotation for Odata that Sonar won’t flag, outside of marking the issue as won’t fix or disabling the rule.
I’ve decided for the moment to switch to the fluent API for the OData, as we had some fluent API where we wanted to control the order of the keys from the default alpha order, although going forward we may switch to using alpha order as the ordering for OData doesn’t need to match the ordering we use for the primary key.
Kind Regards
Chris