akalter
akalter

Reputation: 43

map one class to many classes with type/item

My problem is that i have parent classes, and for each of the parents i have list of classB. for example, the tables are:

Images

id
type
item
filename

computers

id
owner
age

workers

id
name
age

we have many images for every computer and worker. in the classes of computer and worker we have list of images. for the computers the image items are:

id=auto generate
type=1
item= id of computer

for the workers the image items are:

id=auto generate
type=2
item=id of worker

The classes should be: Computers: -id -age -owner -images Workers: -id -age -name -images

About the image, i dont sure what do i need but something like that: -id -filename (optional, if it needed by the mapping) -type -item

some idea how to map that?

Upvotes: 1

Views: 103

Answers (1)

Firo
Firo

Reputation: 30813

class ComputerMap : ClassMap<Computer>
{
    public ComputerMap()
    {
        HasMany(x => x.Images)
            .Where("type = 1")
            .KeyColumn("item")
            .Inverse()
            .Cascade.All();
    }
}

class WorkerMap : ClassMap<Worker>
{
    public WorkerMap()
    {
        HasMany(x => x.Images)
            .Where("type = 2")
            .KeyColumn("item")
            .Inverse()
            .Cascade.All();
    }
}

class ImageMap : ClassMap<Image>
{
    public WorkerMap()
    {
        ReferencesAny(x => x.Item)
            .EntityIdentifierColumn("item")
            .EntityTypeColumn("type")
            .AddMetaValue<Computer>(1)
            .AddMetaValue<Worker>(2)
            .IdentityType<int>();     <-- maybe optional
    }
}

// in Computer and Worker have this
public void AddImage(Image image)
{
    this.Images.Add(image);
    image.Item = this
}

Upvotes: 1

Related Questions