WrongClassException试图实现战略格局的时候(上自己的ID识别) [英] WrongClassException when trying to implement Strategy Pattern (discriminating on own Id)

查看:201
本文介绍了WrongClassException试图实现战略格局的时候(上自己的ID识别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现与功能NHibernate的策略模式,通过的这个博客帖子

I'm trying to implement the Strategy Pattern with Fluent Nhibernate, inspired by 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());
}



以下异常被抛出:

The following exception is thrown:

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

任何帮助调试这个问题,将不胜感激,因为我可以' ŧ弄清楚为什么这是行不通的。

Any help debugging this issue would be appreciated as I can't figure out why this doesn't work.

我可以得到代码通过不歧视上的ID列(并因此创建另一列歧视的)工作,但我觉得这是不能令人满意的,因为它意味着复制数据。

I can get the code to work by not discriminating on the Id column (and so creating another column to discriminate on), but I find this unsatisfactory as it means duplicating data.

这背后的原因是新的策略旨意能够被通过插件架构创建(提供策略 SubclassMap<的实现;策略名称]> 其中获得在应用程序加载读取),因此我需要使用的Guid 太不存在具有ID冲突。

The reasoning behind this is that new Strategys will be able to be created via a plugin architecture (providing an implementation of Strategy and SubclassMap<[strategy-name]> which get read at application load), and as such I need to use Guids so there aren't conflicts with Ids.

推荐答案

似乎在的策略的你正在使用类编号类型的Guid
,但在映射类字符串而不是的Guid 被使用。

Seems that in Strategy class you are using Id of type Guid but in mapper class string instead of Guid is used.

我改变地图类,如下所述,和异常不再出现。

I changed map class as described below, and exception ceased to appear

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

这篇关于WrongClassException试图实现战略格局的时候(上自己的ID识别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆