Home > Software design >  EF Core backing field string array
EF Core backing field string array

Time:11-06

After seeing this page that says:

Backing fields allow EF to read and/or write to a field rather than a property. ... By default, EF will always read and write to the backing field - assuming one has been properly configured - and will never use the property.

I thought I would give it a try. The property is a string array which is not supported by EF Core, so I thought I could use a string as a backing field instead.

    private string ImagesString;
    
    [BackingField(nameof(ImagesString))]
    public string[] Images
    {
        get
        {
            return ImagesString.Split('\n');
        }
        set
        {
            ImagesString = string.Join('\n', value);
        }
    }

My assumption is that EF Core will not try to save Images but only ImagesString which is a plain string. However, when I tried it, I got the same "The property Images could not be mapped because it is of type string[]..." Why is it trying to save Images? Shouldn't it try to save/restore ImagesString only?

CodePudding user response:

Firstly, you forgot to put into OnModelCreating method of DbContext UsePropertyAccessMode (it is also mentioned in the link you provided).

However, then you would get: The specified field 'ImagesString' of type 'string' cannot be used for the property 'Class.Images' of type 'string[]'. Only backing fields of types that are compatible with the property type can be used. Therefore, I assume, EF cannot handle this conversion now.

I would recommend you creating a public method or [NotMapped] property in your entity for the purpose you need.

  • Related