如何使用 EF 存储/映射复杂数据类型?

问题描述 投票:0回答:1

CategoryModel 具有对象画笔类型(复杂数据类型)的属性和依赖属性颜色,无法直接使用 EF 存储,因此我使用序列化并将其存储为字符串。

using System.ComponentModel.DataAnnotations.Schema;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
public class CategoryModel : UserControl{
...
    [NotMapped] // Not mapped to the database
    public Brush Color
    {
        get { return (Brush)GetValue(ColorProperty); }
        set { SetValue(ColorProperty, value); }
    }

    public static readonly DependencyProperty ColorProperty =
    DependencyProperty.Register("Color", typeof(Brush), typeof(CategoryModel), new PropertyMetadata(Brushes.Black));
...
}

所以解决方案是使用 get & set 到 & 从另一个属性我们将其称为 string 类型的 serializedBrush。

问题是:该属性已经使用从依赖属性获取并设置为&。

向 ChatGPT 建议采用这种方法:所以我将依赖属性更改为 serializedBrush 字符串

public class CategoryModel : UserControl{
    ...
    public Brush Color
    {
        get { return JsonSerializer.Deserialize<Brush>(SerializedBrush); }
        set { SerializedBrush = JsonSerializer.Serialize(value); }
    }

    public static readonly DependencyProperty SerializedBrush=
    DependencyProperty.Register("Color", typeof(string), typeof(CategoryModel));
}

AI评论:不要使用依赖属性与数据库交互,它更多地用于处理业务逻辑,并给了我以下解决方案

using System.ComponentModel.DataAnnotations.Schema;
using System.Windows;
using System.Windows.Media;
using System.Text.Json;

namespace YourNamespace
{
    public class CategoryModel : DependencyObject
    {
        
        public static readonly DependencyProperty SerializedBrushProperty =
            DependencyProperty.Register("SerializedBrush", typeof(string), typeof(CategoryModel));
        [Column(TypeName = "nvarchar(max)")] // Specify column type for EF
        public string SerializedBrush
        {
            get { return (string)GetValue(SerializedBrushProperty); }
            set { SetValue(SerializedBrushProperty, value); }
        }

        public Brush Color
        {
            get { return JsonSerializer.Deserialize<Brush>(SerializedBrush); }
            set { SerializedBrush = JsonSerializer.Serialize(value); }
        }
    }
}

但是画笔颜色的依赖属性呢

c# wpf entity-framework dependency-properties
1个回答
0
投票

添加另一个用于序列化的属性或将颜色更改为 RGB

与 < dependency-property > 相关的属性是问题的原因/根源。
因为您将拥有 3 个属性,您需要以某种方式识别它们之间的关系(getter 和 setter)。

解决方案:我们有2个选择:
第一:在DbContext中的“OnModelCreating()”方法中使用值转换,而不是尝试在模型类(CategoryModel)中进行转换。
第二:利用 Entity Framwork Core 8 将复杂类型存储为 JSON 的能力。

谢谢大家,特别感谢 Jeremy Lakeman。

© www.soinside.com 2019 - 2024. All rights reserved.