无法将'NHibernate.Collection.Generic.PersistentGenericSet`1强制转换为System.Collections.Generic.IList`1

时间:2013-05-24 20:16:35

标签: unit-testing nhibernate fluent-nhibernate tdd fluent-nhibernate-test

我有一个域类:

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; }

}

使用此约定(定义为set AsSet

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

当我运行此测试时:

[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
}

如何测试此列表?

  

集合应该是AsSet,父和子字段必须是PK,FK

完整错误:

测试名称:AgenciaTemVariosGerentes 测试FullName:{OMMITED} .Integration.Test.AgenciaTest.AgenciaTemVariosGerentes 测试来源:{OMMITED} .Integration.Test \ AgenciaTest.cs:第22行 测试结果:失败 测试时间:0:00:02,4093555

结果讯息: 测试方法{OMMITED} .Integration.Test.AgenciaTest.AgenciaTemVariosGerentes抛出异常: NHibernate.PropertyAccessException:无效的Cast(检查映射是否存在属性类型不匹配); CreditoImobiliarioBB.Model.Regional的设定者---&gt; System.InvalidCastException:无法转换类型为'NHibernate.Collection.Generic.PersistentGenericSet 1[CreditoImobiliarioBB.Model.Pessoa]' to type 'System.Collections.Generic.IList 1 [CreditoImobiliarioBB.Model.Pessoa]'的对象。 结果StackTrace:
at(Object,Object [],SetterCallback)    在NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(对象目标,对象[]值)    at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity,Object [] values)  ---内部异常堆栈跟踪结束---     at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity,Object [] values)    在NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValues(对象实体,对象[]值)    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)    在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent事件)    在NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent事件)    在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent事件)    在NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent事件)    在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent事件)    在NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent事件)    在NHibernate.Impl.SessionImpl.Save(Object obj)    在FluentNHibernate.Testing.PersistenceSpecification 1.TransactionalSave(Object propertyValue) at FluentNHibernate.Testing.Values.ReferenceProperty 2.HasRegistered(PersistenceSpecification 1 specification) at FluentNHibernate.Testing.PersistenceSpecification 1.RegisterCheckedProperty(Property 1 property, IEqualityComparer equalityComparer) at FluentNHibernate.Testing.PersistenceSpecificationExtensions.CheckReference[T](PersistenceSpecification 1 spec,Expression`1 expression,Object propertyValue,IEqualityComparer propertyComparer)    在{OMMITED} .Integration.Test \ AgenciaTest.cs:第27行的CreditoImobiliarioBB.Repository.Integration.Test.AgenciaTest.AgenciaTemVariosGerentes()中

感谢。

1 个答案:

答案 0 :(得分:11)

集合未实现IList<T>

将您的属性定义为ICollection<T>