15

Assume I have an EF entity class Person, with a PhoneNumber on it. PhoneNumber is stored as a string type, but I want all accesses on the Person to go through Phone which has some nice accessor functions, e.g. validation or GetAreaCode(). I want to back it in the db as a string, but when queried for it I want to return it as a PhoneNumber:

public class Person {
    public PhoneNumber Phone { /* Some clever get/set logic here */ }

    private string _phoneNumber; // Backing field
}

Or can I get PhoneNumber to store itself as a string? If I simply include it in the model by removing the backing field above, EF gets confused by the constructors (a protected ctor with some more args than the one string) and also a copy ctor PhoneNumber(PhoneNumber other). Can i make EF ignore those somehow?

I'm open to ideas...

1

2 Answers 2

14

You can use @nbrosz's answer to fix your issue but you no longer need to do this kind of workaround if you're using EF Core 2.1. You can rid of the backing field by using EF Core 2.1 (which is in Release Candidate 1 since 7 May 2018) you can use the feature of Value Conversion explained here by Microsoft:

Value converters allow property values to be converted when reading from or writing to the database. This conversion can be from one value to another of the same type (for example, encrypting strings) or from a value of one type to a value of another type (for example, converting enum values to and from strings in the database.)

So for your case, you can just remove the backing field. You no longer need it. Your class should look like this:

public class Person 
{
    public PhoneNumber Phone { /* Some clever get/set logic here */ }
}

And in your OnModelCreating method, you configure the conversion like below:

modelBuilder.Entity<Person>()
    .Property(p => p.Phone)
    .HasConversion(
        phone => { 
            // Here you code the logic of how to get the value to store in DB
            return ...;
        },
        dbValue => { 
            // Here you code the logic of how to construct the PhoneNumber instance from the value to store in DB
        }
    );

That's it. Actually it is in release candidate but Microsoft says:

EF Core 2.1 RC1 is a “go live” release, which means once you test that your application works correctly with RC1, you can use it in production and obtain support from Microsoft, but you should still update to the final stable release once it’s available.

This remainder of my answer is for @nbrosz because you are dealing with enum type. You can remove the backing field and also you can one of the many built-in value converters provided by EF Core 2.1. For enum to string value conversion we have the type EnumToStringConverter. For the logic you're doing in your answer, you can just simplify it to this for entity:

[Display(Name = "Fire Type")]
public Enums.FireType Type { get; set; }

We removed the NotMapped attribute on the property and there is no logic y for conversion.

In your OnModelCreating method you do this:

var converter = new EnumToStringConverter<FireType>();

modelBuilder
    .Entity<Fire>()
    .Property(e => e.FireType)
    .HasConversion(converter);

You can also let EF Core detects the right converter for you by using the generic version of HasConversion<T> like below:

modelBuilder
    .Entity<Fire>()
    .Property(e => e.FireType)
    .HasConversion<string>();

If you don't like to use fluent configuration you can use Column data annotation attibute like below and EF Core will do the conversion for you:

[Column(TypeName = "nvarchar(20)")]
[Display(Name = "Fire Type")]
public Enums.FireType Type { get; set; }
6
  • Thanks for the feedback. I'm very much liking the look of this, and it certainly solves what has been a large pain in the butt for me. Too bad our server admins are unlikely to go Core 2.1 any time soon. I can't even get them to go above 2.0.3.
    – nbrosz
    May 17, 2018 at 2:54
  • 1
    @nbrosz you should look for self container application in .Net Core. This allows you to deploy your applications with the runtime so your application will not need the server to install specific runtime. May 17, 2018 at 7:19
  • 1
    I think it is important to mention that custom value converters tend to result in client-side query evaluation. Aug 19, 2019 at 19:14
  • 2
    @MattJenkins you can fix that by using ValueConverterSelector.Check this article for more details. Aug 19, 2019 at 21:16
  • public TimeSpan DeliveryTime { get; set; } and builder.Entity<Product>().Property(p => p.DeliveryTime).HasConversion(p => p.Ticks, p2 => TimeSpan.FromTicks(p2)); gives "Operand type clash: time is incompatible with bigint" error :| on update migration Nov 2, 2020 at 13:46
12

The only way I've found that works in EF Core 2.0 is to create a public property with getters/setters with a name that does not match your backing field and mark it as NotMapped, like so:

    [NotMapped]
    [Display(Name = "Fire Type")]
    public Enums.FireType Type
    {
        get
        {
            Enums.FireType type;
            if (!Enum.TryParse(_fireType, out type))
                type = Enums.FireType.Fire; // default

            return type;
        }
        set
        {
            _fireType = value.ToString();
        }
    }
    
    private string _fireType;

Then in your DbContext's OnModelCreating method, tell it to create a column on the database table that acts like a backing property:

        // backing properties
        modelBuilder.Entity<Fire>()
            .Property<string>("FireType")
            .HasField("_fireType")
            .UsePropertyAccessMode(PropertyAccessMode.Field);

With that, I was finally able to create a successful migration that allowed me to have a private field on my model, a public transformative property on the model, and a single properly-named column in my database table. The only catch is that the public property and the private field can't share the same name (without sharing the same type), but that wasn't going to be the case for you, anyway.

6
  • Very nice! A pity one have to do this kind of trickery, but it did solve my problem. Thanks!
    – bit0001
    Apr 13, 2018 at 15:13
  • Even copy pasting your example does not work and results in an exception: The specified field '_fireType' cannot be used for the property 'Foo.FireType' because it does not match the property name.. EF Core 3.1.
    – Krzaku
    May 22, 2020 at 20:26
  • Agree with Krzaku - at least in 3.1 this does not work, thus the down-vote
    – TadGhostal
    Sep 12, 2020 at 12:00
  • public long _deliveryTime;[NotMapped]public TimeSpan DeliveryTime {get => TimeSpan.FromTicks(_deliveryTime); set => _deliveryTime = value.Ticks; } with .Property<long>(nameof(Product.DeliveryTime)).HasField(nameof(Product._deliveryTime)).UsePropertyAccessMode(PropertyAccessMode.Field); gives following error: "The property 'DeliveryTime' cannot be added to type 'Product' because the type of the corresponding CLR property or field 'TimeSpan' does not match the specified type 'long'." on add migration Nov 2, 2020 at 13:50
  • @deadManN This was a working suggestion when the question was asked (back in 2018, for EF Core 2.0), but this is no longer the recommended solution. Unfortunately, people will keep coming to this old topic and trying old answers. I don't know of any way to clearly mark this as anachronistic.
    – nbrosz
    Nov 17, 2020 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.