Strange exceptions using FluentNHibernate automapping
I have the following entities in my domain model. A group (an aggregate root) contains items (which are aggregate roots themselves) but an item can only be contained by one group at the time. The code below enforces this. The reason for the group to have an Items collection is that in the domain there are certain cases that are most logically solved by providing access items by means of a group.
When I add an item to my group however, I get this FatalExecutionEngineError
:
The runtime has encountered a fatal error. The address of the error was at 0x5f0b8442, on thread 0x99c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
Right after that, a System.ExecutionEngineException
is thrown with no inner exception.
UPDATE
It seems that the _items.Contains(item)
check in the Item.AssignTo
method causes this exception to be thrown. I initially left this check out of the example but I have now added it. When I remove the check, I get an IndexOutOfRangeException
at the _items.Add(item);
statement.
This is my (simplified) domain model:
public class Group : Entity
{
private List<Item> _items = new List<Item>();
public virtual IEnumerable<Item> Ite开发者_高级运维ms
{
get
{
return _items;
}
}
public virtual void Assign(Item item)
{
if (_items.Contains(item))
{
throw new ArgumentException("Already assigned.", "item");
}
_items.Add(item);
}
}
public class Item : Entity
{
public virtual Group Group
{
get;
protected set;
}
public virtual void AssignTo(Group group)
{
group.Assign(this);
this.Group = group;
}
}
The FluentNHibernate mapping overrides:
// AutoMapping<Group>
mapping
.HasMany(n => n.Documents)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Cascade.Delete()
.Inverse();
So, the exception is thrown when I call Item.AssignTo
. When I remove the group.Assign(this);
line from Item.AssignTo
the exception is not raised. But ofcourse, in that case Document.Items
stays empty until the document is retrieved from a repository sometime later.
What am I doing wrong or missing here?
Boy, I wonder what's really going on here. I created a standalone testcase to reproduce the problem but somehow it ran just fine. While I was experimenting some more with the full project, I found that changing private List<Item> _items = new List<Item>();
to private IList<Item> _items = new List<Item>();
, solved the problem!
All of this makes me suspect there is bug in NHibernate somewhere but most of my former bug suspicions regarding external libraries turned out being bugs in my own code so I'm being a bit careful making such accusations.
精彩评论