首页 > 解决方案 > EF Core 支持字段字符串数组

问题描述

看到这个页面后,上面写着:

支持字段允许 EF 读取和/或写入字段而不是属性。...默认情况下,EF 将始终读取和写入支持字段 - 假设已正确配置 - 并且永远不会使用该属性。

我想我会试一试。该属性是 EF Core 不支持的字符串数组,所以我想我可以使用字符串作为支持字段。

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

我的假设是 EF Core 不会尝试保存Images,而只会尝试保存ImagesString纯字符串。但是,当我尝试它时,我得到了相同的“Images无法映射该属性,因为它是类型string[]......”为什么要尝试保存Images?它不应该只尝试保存/恢复ImagesString吗?

标签: c#entity-frameworkentity-framework-core

解决方案


首先,您忘记放入DbContext UsePropertyAccessModeOnModelCreating 方法(在您提供的链接中也提到过)。

但是,您会得到: 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.因此,我认为 EF 现在无法处理此转换。

我建议您根据需要在实体中创建公共方法或 [NotMapped] 属性。


推荐阅读