Entity Framework Core - Has Conversion - Support Null Values

asp.net-core entity-framework entity-framework-core

Question

I have an EF model with a notification emails property. The notification emails are saved in the database as string separated by ';'. I added a conversion to retrieve the data as a ICollection in the model. This is working well except one thing: when the string is null the collection is also null, and I want to convert it to an empty collection instead. is it possible?

//This is my code
  entity.Property(e => e.NotificationEmails)
             .HasConversion(
                v => string.Join(",", v.Select(s => s.Trim())),
                v => v.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

I tried to add String.IsNullOrEmpty(v) but EF ignores it.

1
3
5/13/2019 8:58:00 AM

Popular Answer

Currently, it isn't possible :

https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions#configuring-a-value-converter

A null value will never be passed to a value converter. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties.

But maybe in EF Core 5 : https://github.com/dotnet/efcore/issues/13850

It isn't elegant, but you can use a backing field :

public class Notification
{
    private List<string> _emails = new List<string>();
    public List<string> Emails 
    {
        get => _emails;
        set => _emails = value ?? new List<string>();
    }
}

public class NotificationContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Notification>().Property(d => d.Emails).HasConversion(
                v => string.Join(",", v.Select(s => s.Trim())),
                v => v.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList()
            );
            modelBuilder.Entity<Notification>()
                .Property(b => b.Emails)
                .HasField("_emails")
                .UsePropertyAccessMode(PropertyAccessMode.Property);
    }
}

Note : in where, a empty list will not be translated by null, but by a empty string.

0
3/3/2020 10:05:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow