gpt4 book ai didi

c# - 尝试实现策略模式时出现 WrongClassException(根据自己的 ID 进行区分)

转载 作者:行者123 更新时间:2023-11-30 17:01:07 26 4
gpt4 key购买 nike

我正在尝试使用 Fluent Nhibernate 实现策略模式,灵感来自 this blog post

public abstract class Strategy
{
protected Strategy() { }
protected Strategy(Guid id) { this.Id = id; }
public virtual Guid Id { get; set; }
public abstract void SomeMethod();
}

public class MyStrategy : Strategy
{
public MyStrategy() : base(new Guid("F1CF041B ...")) { }
public override void SomeMethod() { }
}

public class StrategyMap : ClassMap<Strategy>
{
public StrategyMap()
{
this.Id(x => x.Id).GeneratedBy.Assigned();
this.DiscriminateSubClassesOnColumn("Id");
}
}

public class MyStrategyMap : SubclassMap<MyStrategy>
{
public MyStrategyMap()
{
this.DiscriminatorValue("F1CF041B ...");
}
}

但是当我运行以下测试时(其中 this.Session 来自内存数据库):

[TestMethod]
public void CanGetMyStrategy()
{
// Arrange
using (var transaction = this.Session.BeginTransaction())
{
this.Session.Save(new MyStrategy());
transaction.Commit();
this.Session.Clear();
}

// Act
var strategies = this.Session.Query<Strategy>();

// Assert
Assert.IsNotNull(strategies.FirstOrDefault());
}

抛出以下异常:

NHibernate.WrongClassException: 
Object with id: f1cf041b ...
was not of the specified subclass: Namespace.Strategy
(Discriminator was: 'f1cf041b ...')

任何调试此问题的帮助将不胜感激,因为我无法弄清楚为什么这不起作用。


不满意的解决方案

我可以通过不区分 Id 列(并因此创建另一个列来区分)来使代码工作,但我发现这并不令人满意,因为它意味着重复数据。


为什么选择 Guid?

这背后的原因是新的Strategy s 将能够通过插件架构创建(提供在应用程序加载时读取的 StrategySubclassMap<[strategy-name]> 的实现),因此我需要使用 Guid s 所以不会与 ID 发生冲突。

最佳答案

似乎在 Strategy 类中,您使用的是 Guid 类型的 Id但在映射器类中使用 string 而不是 Guid

我如下所述更改了 map 类,异常不再出现

public class MyStrategyMap : SubclassMap<MyStrategy>
{
public MyStrategyMap()
{
this.DiscriminatorValue(new Guid("F1CF041B ..."));
}
}

关于c# - 尝试实现策略模式时出现 WrongClassException(根据自己的 ID 进行区分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21403260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com