简体   繁体   中英

EF Core backing field string array

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?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM