Submit and vote on feature ideas.

Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category.

Explicit Initialization rules are conflicting with Entity Framework

amvankeulen Posts: 3

When trying to do code analysis on web services build using EF Core, I am constantly getting this violation

For this code:

This violation occurs because the DbSet object is build by the DBContext, which does not use explicit initialization

This error is occurring every time I'm accessing a database, which is leading to lots and lots of these violations.

I don’t think suppressing is my best bet, since the use of dbcontext is pretty integral to EF Core, though I'm not sure what a better solution would be

Any ideas on what to do with this?


  • wojciech_bukowicki

    Could you provide the violation with full path? Could you provide code sample showing violation? What I am most interested in is how this _dbContext variable is initialized and where,

  • amvankeulen
    amvankeulen Posts: 3

    Two examples:

    It doesn't look like it's complaining about _dbContext so much as it's complaining about the "Request" and "Check" properties. Both of those don't have explicit initializations, but that's by design. This is what the properties look like in the _dbContext class

    The dbContext is being initialized every time a new API call is made, which looks like this (_dbContext is just assigned this property):

  • wojciech_bukowicki

    As I understand, these properties "Request" and "Check" are somehow implicitly initialized during creation of MyDbContext object.

    I suppose the whole violation path includes assignment of _dbContext variable.

    I have written the reduced sample which I believe reflects the violations you are getting:

    The violation here is correct, as R1 property is not initialized, which will result in NullReferenceException.

    The problem with your code is that the rule does not know anything about implicit initialization and makes conclusions based on the code it sees.
    Possible solution(apart from multiple suppressions) would be to explictly initialize property(if it does not conflict with later implicit initialization). In my case it would be: