Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Maybe patterns for navigations #22504

Open
Tracked by #240
ajcvickers opened this issue Sep 11, 2020 · 2 comments
Open
Tracked by #240

Support Maybe patterns for navigations #22504

ajcvickers opened this issue Sep 11, 2020 · 2 comments

Comments

@ajcvickers
Copy link
Contributor

See discussion here: https://github.com/dotnet/efcore/discussions/22364

Related: #240 #752

@alexmurari
Copy link
Contributor

alexmurari commented Dec 19, 2020

@ajcvickers

Just to give this issue a little bit of context:

The request here is to make navigation properties more flexible:

public class Student
{
    public Course FavoriteCourse { get; set; } // This could be null.
}

In functional programming, we are taught to be more explicit on whether or not a reference type object is null, so we wrap them in a Maybe<T> monad, that works more-or-less like Nullable<T>.

public class Student
{
    private Course _favoriteCourse; // Backing field remains of the same type.
    public Maybe<Course> FavoriteCourse => _favoriteCourse; // Maybe<T> provides implicit conversion.
}

Use it like this:

Maybe<Course> favCourseOrNothing = student.FavoriteCourse;

if (favCourseOrNothing.HasNoValue)
    return Error("Bad student doesn't have a favorite course");

Course favCourse = favCourseOrNothing.Value; // Throws exception if null, preventing us from walking around with null objects.

EF Core doesn't know how to convert Maybe<T> to T, so it gives an exception when building the model.
But, since EF Core works primarily on top of backing fields (and we actually map to the backing field), something like that is totally possible.

  • References

https://github.com/vkhorikov/CSharpFunctionalExtensions#make-nulls-explicit-with-the-maybe-type
https://enterprisecraftsmanship.com/posts/functional-c-non-nullable-reference-types/

@lucasteles
Copy link

I think that having a way to define a NullValueConverter for navigations would be good enough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants