efcore icon indicating copy to clipboard operation
efcore copied to clipboard

GetProperty should return null if not found; instead it throws an exception

Open VAchris opened this issue 4 years ago • 3 comments

We have a disconnect between what the documents say should be happening versus what's implemented.

In the file IReadOnlyEntityType.cs when you try to get a property that does not exist it throws an InvalidOperationException whereas the expected return value is null.

Example

var entityType = MyDbContext.Set<E>().EntityType;
var property = entityType.GetProperty(invalidPropertyName); // this throws an exception

Include stack traces

System.InvalidOperationException: The property 'MyTable.invalidPropertyName' could not be found. Ensure that the property exists and has been included in the model.
   at Microsoft.EntityFrameworkCore.Metadata.IReadOnlyEntityType.GetProperty(String name)
   at Microsoft.EntityFrameworkCore.Metadata.IEntityType.GetProperty(String name)

Include provider and version information

EF Core version: 6.0.3 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 6 Operating system: Windows 10 IDE: VS 2022

VAchris avatar Apr 08 '22 18:04 VAchris

Just wanted to share a workaround I've used in the past which is to use FindProperty instead. Not sure what the semantic difference between Get and Find is but the latter method allows null.

stevendarby avatar Apr 08 '22 19:04 stevendarby

FindProperty is the correct way to do it. GetProperty calls FindProperty under the covers and throws exception if the result is null. We should update the xml docs for GetProperty, as it indicates that null can be returned from GetProperty, which is wrong.

maumar avatar Apr 09 '22 04:04 maumar

I think the exception case not must be workarounded, its safe to know that the problem exist that have a an error in the program logic and dont know why. Just my opinion

KurogamiLight3303 avatar Apr 20 '22 03:04 KurogamiLight3303