How does EF Core's DbContext supress all CS8618 (non-nullable property) warnings?
R

1

2

I know it's an issue in the past since you can search the web and SO for so many questions about getting warning from EF Core model. Today I first use EF Core for .NET 8 and I just realized the warning is not there anymore:

public class AppDbContext : DbContext
{

    public DbSet<DbAccount> Accounts { get; set; }

}

public class MyClass
{

    // The line below still receives this warning:
    // Warning CS8618 Non-nullable property 'Accounts' must contain a non-null value when exiting constructor.Consider declaring the property as nullable:
    public DbSet<DbAccount> Accounts { get; set; }

}

enter image description here

Interestingly it skips for members of DbContext and not DbSet type itself as you can see from the example above, my own class still receive CS8618 warning.

I have tried reading the decompiled code of DbContext and even DbSet and couldn't find anything special. How does EF Core team do that? Can I apply it to my own classes somehow (for POCO JSON classes for example)?

Ragged answered 7/5 at 8:48 Comment(2)
For stuff I know will be set by a deserializer or similar, I just public string MyProp{get;set;} = default!; or if there are a lot of them I toggle it off with #nullable ... but I take it you're asserting to have code that doesn't do this or anything like it, nor any #nullable disable etc, but still you see no warning in the code generated by ef tools, but you do see warning in your own code?Orangeade
@Orangeade yeah I already use null! and #nullable false currently but I am surprised EF Core could somehow did that without. The above example code I gave is from the same file, DbContext derived class doesn't get any warning but my own class gets it. That's why I am curious and want to know how to do that.Ragged
L
2

Suppressing Warning CS8618 is done by EFCore.Analyzers package.

Check source code for such analyzer UninitializedDbSetDiagnosticSuppressor

Liturgist answered 7/5 at 9:12 Comment(2)
Very interesting! Now I know where to start reading. Thanks a lot. I guess this article is a good start.Ragged
The GitHub issue : Write a DiagnosticSuppressor for CS8618 for DbSet propertiesCommie

© 2022 - 2024 — McMap. All rights reserved.