您好,我正在使用使用 telerik orm 的旧代码。 MSSQL 数据库的基础是从后端迁移的 db2 。
我知道 db2 在表中存储布尔值不提供专用类型。这个问题有不同的解决方法。在我的情况下,决定使用自定义SQL Type BITTYPE:char(1)
,实际上它保留了两个方面的 char(1(值('1' (true)
和'0' (false)
(。 Telerik Orm 使用自定义AdoTypeConverter
将此字符(1(值转换为域 boolean properties 。
public class BitTypeToBooleanConverter : TypeConverterBase
{
public BitTypeToBooleanConverter()
{
this.ConverterType = typeof(bool);
this.NullableConverterType = typeof(bool?);
}
public override object Read(ref DataHolder holder)
{
bool n = holder.Reader.IsDBNull(holder.Position);
holder.NoValue = n;
if (n)
{
if (nullable)
holder.ObjectValue = null;
else if (holder.Box)
holder.ObjectValue = false;
else
holder.BooleanValue = false;
}
else
{
string s = holder.Reader.GetValue(holder.Position).ToString();
bool outValue = false;
if (!bool.TryParse(s,out outValue))
{
if (s.Equals("1"))
{
outValue = true;
}
}
if (nullable || holder.Box)
holder.ObjectValue = outValue;
else
holder.BooleanValue = outValue;
}
return (holder.Box || nullable) ? holder.ObjectValue : null;
}
public override void Write(ref DataHolder holder)
{
holder.Parameter.DbType = System.Data.DbType.String;
if (holder.NoValue)
{
holder.Parameter.Size = 1;
holder.Parameter.Value = null;
}
else
{
string s = (holder.BooleanValue ? "1" : "0");
holder.Parameter.Size = s.Length;
holder.Parameter.Value = s;
}
}
public override bool CreateLiteralSql(ref DataHolder holder)
{
if (holder.NoValue)
{
holder.StringValue = "NULL";
return false;
}
else
{
holder.StringValue = (holder.BooleanValue ? "1" : "0");
return true; // inidicating that ' are needed around, because it is a character column (VARCHAR)
}
}
Q:我无法更改数据库,但是我需要以某种方式教授 Entity Framework orm 在相同的情况下工作
P.S 我阅读了文章(
(- https://msdn.microsoft.com/en-us/library/jj819164(v = vs.113(.aspx(,
我尝试使用"使用惯例"解决此问题,但没有带来结果。
- bittype:char(1( - 错误:在SQLServer提供者清单中找不到
- char - **错误:**指定的模式无效。错误: (8,12(:2019年错误:指定的成员映射无效。..
代码段:
public class BitTypeCharConvention : Convention
{
private const string DataType = "BITTYPE:char(1)";
public BitTypeCharConvention()
{
Properties<bool>().Configure(c => c.HasColumnType(DataType));
}
}
我也知道我可以尝试创建另一个将转换字符串值的属性,但是我想更多"可重复使用" variant
结论:通过,在随机搜索后,我实际上还没有找到适合额头解决方案的解决方案。因此,决定在数据访问级别(不要进行任何转换(与默认实体框架行为保持联系,并通过映射(IE AutomApper((IE实体到域模型(在下一个应用程序级别上进行此工作。