0
votes

I'm having troubles creating the relations using Fluent NHibernate. Generally, i have two tables, resource & items:

Resource & Items

please notice that PK in the resources table is both id AND locale. it means that, one item can actually have few resources (same id but different locale).

because it's not a one to one simple relation i'm having troubles mapping those two using Fluent NHibernate.

What's the right way to overcome this?

Thanks a lot!

1
Is it a many to many relationship, i.e. can a given resource (as identified by its {id, locale} composite key) be referenced by different items?Alex
generally no. but it sounds like using a many to many design can make it simplier no?rotem

1 Answers

0
votes

If the relationship is such that a given Resource is owned by a single given Item, this could be modeled like this (note: parts that matter included only):

public class Item
{
    public virtual int Id { get; protected set; }
    public virtual IList<Resource> Resources { get; protected set; }
    // Constructor, Equals, GetHashCode, other things ... omitted.
}

public class Resource
{
    public virtual Item Owner { get; protected set; }
    public virtual int ResourceId { get; protected set; }
    public virtual string Locale { get; protected set; }
    public virtual string Value { get; protected set; }
    // Constructor, Equals, GetHashCode, other things ... omitted.
}

And create the following class maps:

public class ItemMap : ClassMap<Item>
{
    public ItemMap()
    {
        WithTable("items");
        Id(x => x.Id); // add Id generation cfg if needed
        HasMany(x => x.Resources)
            .Inverse()
            .Cascade.All()
    }
}

public class ResourceMap : ClassMap<Resource>
{
    public ResourceMap()
    {
        WithTable("resources")
        CompositeId()
            .KeyProperty(x => x.ResourceId)
            .KeyProperty(x => x.Locale);
        References(x => x.Owner)
    }
}