繁体   English   中英

EF Core 支持字段字符串数组

[英]EF Core backing field string array

看到这个页面后,说:

支持字段允许 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吗?

首先,你忘了投入的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. 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] 属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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