How do I automap a component collection in Fluent NHibernate?
I have a TrackLog
that contains a collection of GPS points as a TrackPoint
object:
public class TrackPoint
{
public virtual int Id { get; set; }
public virtual List<TrackPoint> TrackPoints { get;set; }
}
public class TrackLog
{
public virtual double Latitude { get; set; }
public virtual double Longitude { get; set; }
public virtual DateTime Timestamp { get; set; }
}
TrackPoint
is a component and I've created an IAutomappingConfiguration
that tells FNH to map it as such. However, when I t开发者_C百科ry to run my program, FNH spits out the following exception:
Association references unmapped class: TestProject.Components.TrackPoint
How do I map a collection of components?
I figured out my problem. Rafael, in response to your question, TrackLog
has a collection of TrackPoints
. Normally in this case, TrackPoint
would be an entity, but because a TrackPoint
should not exist if it doesn't belong in a TrackLog
, I decided to make it a component, which ties its lifetime to its parent TrackLog
.
It turns out the problem I was having was that, even though I created an automapping override, it wasn't working:
internal class TrackLogOverride : IAutoMappingOverride<TrackLog>
{
public void Override(AutoMapping<TrackLog> mapping)
{
mapping.HasMany(x => x.TrackPoints).Component(x =>
{
x.Map(m => m.Latitude);
x.Map(m => m.Longitude);
x.Map(m => m.Timestamp);
});
}
}
Turns out that I needed to make the override class public
for FNH to use them because I was using FNH in another assembly.
The very first thing that needs to change is to change the List
type to IList
. The reason for needs is because NHibernate needs to inject its own type of collection, not C#'s own List
.
What I don't understand is TrackPoint per se. You're saying that it's a component consuming itself? Could you give us more insight? I'm confused.
Say I have a class Track which consumes TrackPoint as a component:
public class TrackMap : ClassMap<TrackPoint>
{
Id(x => x.Id);
Component(x => x.TrackPoint, m =>
{
m.Map(x => x.Id);
// Try one of the following (not sure):
m.Map(x => x.TrackPoints);
m.HasMany(x => x.TrackPoints);
}
}
Does this help?
精彩评论