简体   繁体   中英

Fluent nHibernate Mapping HasMany Composite Key with Fixed Value

I'm trying to implement nHibernate mapping for a large exisiting system. trying to map the relationship between two object. One object is "Attachments" which relate to a number of different objects across the system. So in the database it has two columns which it uses to relate itself

ItemType

ItemId

If I have a product with attachments on then ProductId = ItemId and ItemType will be a predefined value Eg '0001' Where as User object might be '0002', Order might be '0003' and so on for other ItemTypes.

Now I need to map this in nhibernate. So I want to have a collections of attachments on the Product Object but this means mapping it across both ItemId and ItemType

If it was just the ItemId mapping that was required it could do

HasMany(x => x.Attachments).KeyColumn("ProductId");

But Instead I need to map it where KeyColumn "ProductId" and ItemType in Attachments table is equal to '0001'

How could I go about this...?

Structure Product table

[Product]

ProductId

Name

Description

Attachment table

[Attachment]

AttachmentURL

ItemId

ItemType

What I would do is create a base, abstract Attachment type like so:

public abstract class Attachment
{
    public TYPE AttachmentURL { get; set; }
}

Then make a subclass for each attachment 'type':

public class ProductAttachment : Attachment
{
    protected ProductAttachment() { }

    public ProductAttachment(Product parent)
    {
        Parent = parent;
    }

    public Product Parent { get; protected set; }
}

Then, in your Attachment mapping you will include this line:

DiscriminateSubClassesOnColumn("ItemType");

And then add a 'DiscriminatorValue' call to each of the subclass mappings. For example:

// Inside ProductAttachment mapping
...
DiscriminatorValue("0001");
...

Then, just map everything as you would normally. This gives the added benefit that your Product will have a list of 'ProductAttachment' which would require the 'parent' to be a Product.

There might be some weirdness when getting just the base type 'Attachment' (as opposed to 'ProductAttachment') from the database but you can cross that bridge when/if it comes.

Found the answer here

Fluent Nibernate putting a where clause in the mapping

I can hard code the mapping like so

HasMany(x => x.Children).Where("ItemType='0001'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM