Jus*_*ica 7 c# castle-activerecord automapper automapper-4
我正在努力在我们的服务中实现AutoMapper,并且在我们的单元测试中看到了一个非常令人困惑的问题.
首先,此问题涉及以下对象及其各自的映射:
public class DbAccount : ActiveRecordBase<DbAccount>
{
// this is the ORM entity
}
public class Account
{
// this is the primary full valued Dto
}
public class LazyAccount : Account
{
// this class as it is named doesn't load the majority of the properties of account
}
Mapper.CreateMap<DbAccount,Account>();
//There are lots of custom mappings, but I don't believe they are relevant
Mapper.CreateMap<DbAccount,LazyAccount>();
//All non matched properties are ignored
Run Code Online (Sandbox Code Playgroud)
它也涉及这些对象,但此时我还没有使用AutoMapper映射这些对象:
public class DbParty : ActiveRecordBase<DbParty>
{
public IList<DbPartyAccountRole> PartyAccountRoles { get; set; }
public IList<DbAccount> Accounts {get; set;}
}
public class DbPartyAccountRole : ActiveRecordBase<DbPartyAccountRole>
{
public DbParty Party { get; set; }
public DbAccount Account { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这些类使用包含以下内容的自定义代码进行转换,其中source包含DbParty:
var party = new Party()
//field to field mapping here
foreach (var partyAccountRole in source.PartyAccountRoles)
{
var account = Mapper.Map<LazyAccount>(partyAccountRole.Account);
account.Party = party;
party.Accounts.Add(account);
}
Run Code Online (Sandbox Code Playgroud)
我遇到问题的测试创建了一个新的DbParty,两个新的DbAccounts链接到新的DbParty,两个新的DbPartyAccountRoles都链接到新的DbParty,每个DbAccounts都有1个.然后,它通过DbParty存储库测试一些更新功能.如果需要,我可以包含一些代码,只需要一些时间来擦洗.
当它自己运行时,这个测试工作正常,但是当在另一个测试的同一个会话中运行时(我将在下面详述),上面的转换代码中的Mapper调用抛出了这个异常:
System.InvalidCastException : Unable to cast object of type '[Namespace].Account' to type '[Namespace].LazyAccount'.
Run Code Online (Sandbox Code Playgroud)
另一个测试也会创建一个新的DbParty,但只有一个DbAccount,然后创建3个DbPartyAccountRoles.我能够将这个测试缩小到打破其他测试的确切线,它是:
Assert.That(DbPartyAccountRole.FindAll().Count(), Is.EqualTo(3))
Run Code Online (Sandbox Code Playgroud)
注释掉这一行可以让另一个测试通过.
有了这些信息,我猜测测试是因为与调用AutoMapper时DbAccount对象后面的CastleProxy有关,但我对此没有任何想法.
我现在设法运行相关的功能测试(对服务本身进行调用)并且它们似乎工作正常,这使我认为单元测试设置可能是一个因素,最值得注意的是有问题的测试是针对内存数据库中的SqlLite.
小智 0
该问题最终与在单元测试中多次运行 AutoMapper Bootstrapper 有关;调用是在我们的测试基类的 TestFixtureSetup 方法中进行的。
修复方法是在创建地图之前添加以下行:
Mapper.Reset();
Run Code Online (Sandbox Code Playgroud)
我仍然很好奇为什么这是唯一有问题的地图。
| 归档时间: |
|
| 查看次数: |
515 次 |
| 最近记录: |