EF Core 支持字段字符串数组
EF Core backing field string array
看到 this page 后说:
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.
我想我会试一试。 属性 是一个不受 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
,这是一个纯字符串。然而,当我尝试它时,我得到了相同的“The 属性 Images
could not be mapped because it is of type string[]
...” 为什么它试图保存 Images
?它不应该尝试 save/restore ImagesString
吗?
首先,您忘记将 OnModelCreating 方法放入 DbContext UsePropertyAccessMode 方法(它是在您提供的 link 中也提到了。
然而,你会得到:
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 现在无法处理此转换。
我建议您根据需要在实体中创建 public 方法或 [NotMapped] 属性。
看到 this page 后说:
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.
我想我会试一试。 属性 是一个不受 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
,这是一个纯字符串。然而,当我尝试它时,我得到了相同的“The 属性 Images
could not be mapped because it is of type string[]
...” 为什么它试图保存 Images
?它不应该尝试 save/restore ImagesString
吗?
首先,您忘记将 OnModelCreating 方法放入 DbContext UsePropertyAccessMode 方法(它是在您提供的 link 中也提到了。
然而,你会得到:
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 现在无法处理此转换。
我建议您根据需要在实体中创建 public 方法或 [NotMapped] 属性。