开发者

nHibernate Exception: Unable to cast object of type

I am running into an nHibernate error while saving an object.

The classes involved are:

interface IHardwareSpecification
{
   //fields and methods
} 

public c开发者_C百科lass CPUSpecification : IHardwareSpecification
{
    //fields and methods
}    

public class SystemTransaction 
{       
    //Bunch of other fields

    private IHardwareSpecification _specs;
    public virtual IHardwareSpecification Specification 
    { 
        get { return _specs; }
        set { _specs = value;} 
    }
 }

Mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ...>
  <class name="SystemTransaction" table="SystemTransactions" lazy="false">
    <component access="field.camelcase-underscore" name="Specification"
               class="HardwareMarketplace.Model.CPUSpecification">
      <property access="field.camelcase-underscore" column="Specification_Rate"
                name="Rate"/>
         ...
    </component>
  </class>
</hibernate-mapping >

While persisting the object to database via Save, I get the following error:

Exception: Unable to cast object of type 'Castle.Proxies.IHardwareSpecificationProxy' to type 'Hardwaremarketplace.Model.SystemTransactions.CPUSpecification'.

I am trying to figure out how to resolve this so any help will be appreciated. f


Based on your comment I understand that AutoMapper creates proxy type for interface property Specification. Thus you have:

public class CPUSpecification : IHardwareSpecification { }

and

public class IHardwareSpecificationProxy : IHardwareSpecification{ }

These are two incompatible types and IHardwareSpecificationProxy object cannot be converted to CPUSpecification.

What you need to do is to tell AutoMapper to use CPUSpecification class instead of dynamic proxy.

Edit: Considering you have CPUSpecificationDTO inside SystemTransactionDTO, you can achieve what you need with the following code:

Mapper.CreateMap<SystemTransactionDTO, SystemTransaction>();
Mapper.CreateMap<CPUSpecificationDTO, CPUSpecification>();
Mapper.CreateMap<CPUSpecificationDTO, IHardwareSpecification>()
    .ConvertUsing(dto => Mapper.Map<CPUSpecificationDTO, CPUSpecification>(dto));

And no need to change Specification property type to CPUSpecification:).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜