首先,让我为这篇文章的长度道歉,虽然这主要是代码,所以我希望你们都能容忍我!
我有一个处理遗留数据库的场景,在这里,我需要使用IUserType 3.2编写一个NHibernate,以获得一个2个字符的“状态”字段,并从其中返回一个布尔值。status字段可以保存3个可能的值:
* 'DI' // 'Disabled', return false
* ' ' // blank or NULL, return true
* NULL 以下是我简化的内容。
表定义:
CREATE TABLE [dbo].[Client](
[clnID] [int] IDENTITY(1,1) NOT NULL,
[clnStatus] [char](2) NULL,
[clnComment] [varchar](250) NULL,
[clnDescription] [varchar](150) NULL,
[Version] [int] NOT NULL
)Fluent映射:
public class ClientMapping : CoreEntityMapping<Client>
{
public ClientMapping()
{
SchemaAction.All().Table("Client");
LazyLoad();
Id(x => x.Id, "clnId").GeneratedBy.Identity();
Version(x => x.Version).Column("Version").Generated.Never().UnsavedValue("0").Not.Nullable();
OptimisticLock.Version();
Map(x => x.Comment, "clnComment").Length(250).Nullable();
Map(x => x.Description, "clnDescription").Length(250).Nullable();
Map(x => x.IsActive, "clnStatus").Nullable().CustomType<StatusToBoolType>();
}
}我的IUserType实现:
public class StatusToBoolType : IUserType
{
public bool IsMutable { get { return false; } }
public Type ReturnedType { get { return typeof(bool); } }
public SqlType[] SqlTypes { get { return new[] { NHibernateUtil.String.SqlType }; } }
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return cached;
}
public object Disassemble(object value)
{
return value;
}
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x == null ? typeof(bool).GetHashCode() + 473 : x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var obj = NHibernateUtil.String.NullSafeGet(rs, names[0]);
if (obj == null) return true;
var status = (string)obj;
if (status == " ") return true;
if (status == "DI") return false;
throw new Exception(string.Format("Expected data to be either empty or 'DI' but was '{0}'.", status));
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var parameter = ((IDataParameter) cmd.Parameters[index]);
var active = value == null || (bool) value;
if (active)
parameter.Value = " ";
else
parameter.Value = "DI";
}
}不过,这不管用。此单元测试因计数不准确而失败。
[TestMethod]
public void GetAllActiveClientsTest()
{
//ACT
var count = Session.QueryOver<Client>()
.Where(x => x.IsActive)
.SelectList(l => l.SelectCount(x => x.Id))
.FutureValue<int>().Value;
//ASSERT
Assert.AreNotEqual(0, count);
Assert.AreEqual(1721, count);
}它失败的原因是它生成了以下SQL:
SELECT count(this_.clnID) as y0_ FROM Client this_ WHERE this_.clnstatus = @p0;
/* @p0 = ' ' [Type: String (0)] */但我需要它来生成这个:
SELECT count(this_.clnID) as y0_ FROM Client this_ WHERE (this_.clnstatus = @p0 <b> OR this_.clnstatus IS NULL);</b>经过一些调试,我看到在生成查询之前调用了StatusToBoolType类中的StatusToBoolType()方法,因此我能够通过在该方法中编写一些恶意代码来操作cmd.CommandText属性中的cmd.CommandText。
...
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var parameter = ((IDataParameter) cmd.Parameters[index]);
var active = value == null || (bool) value;
if (active)
{
parameter.Value = " ";
if (cmd.CommandText.ToUpper().StartsWith("SELECT") == false) return;
var paramindex = cmd.CommandText.IndexOf(parameter.ParameterName);
if (paramindex > 0)
{
// Purpose: change [columnName] = @p0 ==> ([columnName] = @p0 OR [columnName] IS NULL)
paramindex += parameter.ParameterName.Length;
var before = cmd.CommandText.Substring(0, paramindex);
var after = cmd.CommandText.Substring(paramindex);
//look at the text before the '= @p0' and find the column name...
var columnSection = before.Split(new[] {"= " + parameter.ParameterName}, StringSplitOptions.RemoveEmptyEntries).Reverse().First();
var column = columnSection.Substring(columnSection.Trim().LastIndexOf(' ')).Replace("(", "");
var myCommand = string.Format("({0} = {1} OR {0} IS NULL)", column.Trim(), parameter.ParameterName);
paramindex -= (parameter.ParameterName.Length + column.Length + 1);
var orig = before.Substring(0, paramindex);
cmd.CommandText = orig + myCommand + after;
}
}
else
parameter.Value = "DI";
}但这是NHibernate!像这样对sql语句进行黑客攻击不可能是正确的处理方法?对吗?
因为它是一个共享的遗留数据库,所以我不能将表模式更改为NULL,否则我只会这样做,并且避免了这种情况。
最后,在这一切之后,我的问题很简单,我在哪里可以告诉NHibernate为这个IUserType生成一个自定义的IUserType标准语句?
提前谢谢大家!
发布于 2012-01-10 23:09:37
解决了!
在我发布了我的问题后,我回到了绘图板上,我想出了一个解决方案,它不需要侵入IUserType实现中生成的SQL。事实上,这个解决方案根本不需要IUserType!
这就是我所做的。
首先,我更改了IsActive列,以使用一个公式来处理空检查。这解决了QueryOver失败带来的问题,因为现在每当NHibernate处理IsActive属性时,它都会注入我的sql公式来处理null。
这种方法的缺点是,在我输入公式之后,我所有的保存测试都失败了。结果表明,公式性质实际上是ReadOnly性质。
因此,为了解决这个问题,我向实体添加了一个受保护的属性,以保存数据库中的status值。
接下来,我将IsActive属性更改为将受保护状态属性设置为“”或"DI“。最后,我将FluentMapping更改为将受保护状态属性显示为NHibernate,以便NHibernate能够跟踪它。既然NHibernate知道了状态,就可以在其INSERT/UPDATE语句中包含它。
我将在下面列出我的解决方案,以防其他人感兴趣。
客户端类
public class Client
{
...
protected virtual string Status { get; set; }
private bool _isActive;
public virtual bool IsActive
{
get { return _isActive; }
set
{
_isActive = value;
Status = (_isActive) ? " " : "DI";
}
}
}更改为Fluent映射
public class ClientMapping : CoreEntityMapping<Client>
{
public ClientMapping()
{
....
Map(Reveal.Member<E>("Status"), colName).Length(2);
Map(x => x.IsActive).Formula("case when clnStatus is null then ' ' else clnStatus end");
}
}https://stackoverflow.com/questions/8796879
复制相似问题