Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast 'NHibernate.Collection.Generic.PersistentGenericSet`1 to System.Collections.Generic.IList`1

I have a domain class:

public class Agencia : IEntity
{
    public virtual int Id { get; set; }

    public virtual string Nome { get; set; }

    public virtual string Identificacao { get; set; }

    public virtual IList<Pessoa> Gerentes { get; protected set; }

    public Agencia()
    {
        Gerentes = new List<Pessoa>();
    }

    public virtual void AddGerente(Pessoa gerente)
    {
        Gerentes.Add(gerente);
    }
    public virtual void AddGerentes(params Pessoa[] gerentes)
    {
        Parallel.ForEach(gerentes, (pessoa) => Gerentes.Add(pessoa));
    }
}

public class Pessoa: IEntity
{
    public virtual int Id { get; set; }

    public virtual string Nome { get; set; }

}

With this convention (defined as set AsSet)

public class AgenciaConvention : IAutoMappingOverride<Agencia>
{
    public void Override(AutoMapping<Agencia> mapping)
    {
        mapping.HasManyToMany(a => a.Gerentes).Cascade.AllDeleteOrphan().AsSet().Not.Inverse();
    }
}

When I run this test:

[TestMethod]
[Description("Uma agência tem vários gerêntes")]
public void AgenciaTemVariosGerentes()
{
    // Arrange
    var fix = new Fixture();
    var currentUser = GetLoggedUser();

    // Create a List<Pessoa>

    var gerentes = fix.Build<Pessoa>()
                        .With(p => p.Nome)
                        .With(p => p.CPF)
                        .With(p => p.CreateBy, currentUser)
                        .OmitAutoProperties()
                        .CreateMany<Pessoa>(10).ToList();

    // Action

    new PersistenceSpecification<Agencia>(Session)
            .CheckProperty(p => p.Nome, fix.Create<string>().Truncate(80))
            .CheckProperty(p => p.Identificacao, fix.Create<string>().Truncate(10))
            .CheckReference(p => p.Regional,
                fix.Build<Regional>()
                    .With(p => p.Nome)
                    .OmitAutoProperties()
                    .Create()
            , new IDEqualityComparer())
            .CheckList(p => p.Gerentes, gerentes, new IDEqualityComparer())
            .CheckReference(p => p.CreateBy, currentUser, new IDEqualityComparer())
            .VerifyTheMappings(); // Assert
}

How can I test this list?

The collection should be AsSet, it necessary that the Parent and Children fields are PK, FK

Full Error:

Test Name: AgenciaTemVariosGerentes Test FullName: {OMMITED}.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes Test Source: {OMMITED}.Integration.Test\AgenciaTest.cs : line 22 Test Outcome: Failed Test Duration: 0:00:02,4093555

Result Message: Test method {OMMITED}.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes threw exception: NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of CreditoImobiliarioBB.Model.Regional ---> System.InvalidCastException: Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[CreditoImobiliarioBB.Model.Pessoa]' to type 'System.Collections.Generic.IList1[CreditoImobiliarioBB.Model.Pessoa]'. Result StackTrace:
at (Object , Object[] , SetterCallback ) at NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) --- End of inner exception stack trace --- at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValues(Object entity, Object[] values) at NHibernate.Persister.Entity.AbstractEntityPersister.SetPropertyValues(Object obj, Object[] values, EntityMode entityMode) at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.Save(Object obj) at FluentNHibernate.Testing.PersistenceSpecification1.TransactionalSave(Object propertyValue) at FluentNHibernate.Testing.Values.ReferenceProperty2.HasRegistered(PersistenceSpecification1 specification) at FluentNHibernate.Testing.PersistenceSpecification1.RegisterCheckedProperty(Property1 property, IEqualityComparer equalityComparer) at FluentNHibernate.Testing.PersistenceSpecificationExtensions.CheckReference[T](PersistenceSpecification1 spec, Expression`1 expression, Object propertyValue, IEqualityComparer propertyComparer) at CreditoImobiliarioBB.Repository.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes() in {OMMITED}.Integration.Test\AgenciaTest.cs:line 27

Thanks.

like image 613
ridermansb Avatar asked May 24 '13 20:05

ridermansb


1 Answers

Sets don't implement IList<T>.

Define your properties as ICollection<T> instead.

like image 153
Diego Mijelshon Avatar answered Nov 17 '22 00:11

Diego Mijelshon