每个子类的nhibernate表"无效的演员"例外

时间:2015-02-20 21:19:53

标签: c# nhibernate fluent-nhibernate

使用table-per-subclass模式面临一些奇怪的问题。我创建了一些对象(Bid,见下文),并使用ISession方法SaveOrUpdate(obj)将其添加到DB。它工作正常,我的表更新正确。但是当我想通过调用方法Get(type,key)获取此对象时,我收到错误“InvalidCastException:System.String”。
经过一小时的反编译后,我收到了有关错误的更多信息:“无效的强制转换异常:无法将System.String强制转换为DocumentHolder”。我真的很困惑,因为在我的代码中我没有看到从String到DocumentHolder的任何可能的转换 您可以在下面看到代码。 (我已经从课程中删除了所有不必要的项目)

public abstract class DocumentHolder
{
    public DocumentHolder(){}
    public DocumentHolder(string Id)
    {
        this.Id = Id;
    }

    public virtual string Id { get; set; }
    //each subentity has it own Type
    public abstract string EntityType { get; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        var t = obj as DocumentHolder;
        if (t == null)
            return false;
        if (Id == t.Id && EntityType == t.EntityType)
            return true;
        return false;
    }
    public override int GetHashCode()
    {
        return (Id + "|" + EntityType).GetHashCode();
    }
}
//Map implementation (simple composite id)
class DocumentHolderMap:ClassMap<DocumentHolder>
{
    public DocumentHolderMap()
    {
        this.CompositeId()
            .KeyProperty(x => x.Id, x => x.Length(50))
            .KeyProperty(x => x.EntityType, x => x.Access.ReadOnly()
                .ColumnName("entity_type"));
    }
}

我也有一个孩子:

public class Bid : DocumentHolder
{
  public override string EntityType
    {
        get { return "bid"; }
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        var t = obj as Bid;
        if (t == null)
            return false;
        if (Id == t.Id && EntityType == t.EntityType)
            return true;
        return false;
    }
    public override int GetHashCode()
    {
        return (Id + "|" + EntityType).GetHashCode();
    }
}
class BidMap : SubclassMap<Bid>
{
   public BidMap()
   {
       KeyColumn("id");
       KeyColumn("entity_type");
   }
}

代码中的某处:

//creating a Bid bid;
session.SaveOrUpdate(bid); //works fine
var newBid = session.Get(typeof(Bid),bid.Id); //throws InvalidCastException

1 个答案:

答案 0 :(得分:1)

哦,我的错。 因为我有一个带有复合键的类,我需要通过复合id来获取它()。不只是字符串ID。工作代码:

session.Get(new Bid(Id = "balbal")); //there is the key field "EntityName" generated by default (as it readonly)

但是异常消息确实没有提供信息。

相关问题