c# - 是否可以使用实体框架 6 将实体的多个属性读/写到单个列中?如何?
问题描述
给定以下模型(User和Xyz),我希望 Entity Framework 将 User 的 Xyz 属性写入单个列,而不是创建并将它们写入三列(Xyz_X、Xyz_Y、Xyz_Z)。
- 是否可以为实体框架自定义序列化器/反序列化器来做到这一点?
- 如何?
谢谢!
楷模:
public class Xyz
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public static implicit operator string(Xyz d) => $"{d.X};{d.Y};{d.Z}";
public static implicit operator Xyz(string s)
{
var separators = new char[] { ';' };
var t = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return new Xyz
{
X = int.Parse(t[0]),
Y = int.Parse(t[1]),
Z = int.Parse(t[2]),
};
}
}
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public Xyz Xyz { get; set; }
}
上述模型的数据库表
用户表现在(当前):
ID | 姓名 | Xyz_X | XYZ_Y | XYZ_Z |
---|---|---|---|---|
1 | 爱丽丝 | 0 | 1 | 2 |
2 | 鲍勃 | -1 | 999 | 777 |
具有自定义序列化/反序列化的用户表(我想要的):
ID | 姓名 | XYZ |
---|---|---|
1 | 爱丽丝 | 0;1;2 |
2 | 鲍勃 | -1;999;777 |
更新:使用解决方法
由于EF6不支持ValueConverter(请参阅评论!)并且我无法将整个项目更改/重写/迁移到Core 3.1,因此我使用了以下解决方法:
- 向User类添加了第二个属性DbXyz
- 为User类的Xyz属性添加了NotMapped属性
现在EF在读取/写入时忽略属性Xyz ,但属性DbXyz被滥用为属性 Xyz 的转换器。
重要的是注释和命名新的“转换器”属性DbXyz,以便其他开发人员了解不要在他们的算法中使用 get/set,而是使用Xyz属性。
public class Xyz
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public override string ToString() => $"{X};{Y};{Z}";
public static implicit operator string(Xyz d) => d.ToString();
public static implicit operator Xyz(string s)
{
var separators = new char[] { ';' };
var t = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return new Xyz
{
X = int.Parse(t[0]),
Y = int.Parse(t[1]),
Z = int.Parse(t[2]),
};
}
}
public class User
{
public int ID { get; set; }
public string Name { get; set; }
[NotMapped]
public Xyz Xyz { get; set; }
// Used only to read/write from database!
public string DbXyz
{
get => Xyz.ToString();
set => Xyz= value;
}
}
解决方案
推荐阅读
- mysql - 如何从另一个托管服务提供商向 MySQL 数据库添加新用户?
- reactjs - 来自服务器的 Redux 初始状态
- linux - 如果列匹配,则在匹配前打印一行
- java - 如何修复:java.lang.IllegalStateException:提交响应后无法转发
- dialogflow-es - 有没有办法使用 Dialogflow 从电报机器人获取用户坐标?
- python - 如何更有效地遍历大型 CSV 文件?
- css - 在 Bootstrap 4 中自定义 .input-group-append
- python - 数据库重启时 SqlAlchemy 崩溃
- c - 我不太明白它添加 5 位输入总和的语法
- java - 矢量绘图的奇怪问题。ImageView 中的锯齿状边缘