Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentNhibernate mapping of two tables oneToMany using unique instea of primary key in mapping

Tags:

I' m writing desktop Project in C#. I'm using Nhibernate to communicate with database. Moreover I use FluentNhibernate into mapping of models but I'm stuck in some part of mapping. Here is My mapping Class in ProductMap

Loosing Map

   public LosingMap()
        {
            Id(x => x.id);
            Map(x => x.reason);
            Map(x => x.quantity);
            Map(x => x.lose_sum);
            Map(x => x.rate);
            Map(x => x.deleted);
            Map(x => x.create_date);
            Map(x => x.update_date);
            References(x => x.currency).Column("CurrencyCode");
            Table("Loosing");


        }
    }

here is CurrencyMap

CurrencyMap

public CurrencyMap()
    {

        Id(x => x.id);
        Map(x => x.code).UniqueKey("currency_code");


        Map(x => x.name);
        Map(x => x.shname);
        Map(x => x.symbol);
        Map(x => x.deleted);
        HasMany(x => x.Losings).Cascade.All();
        Table("currency");
    }
}

here is I have in my currency table one primary key and one unique key how I can refer in my LoosingMap class my unique instead of primary key ???

like image 811
Jahongir Sabirov Avatar asked Aug 16 '18 08:08

Jahongir Sabirov


1 Answers

Use KeyColumn on the CurrencyMap use:

public CurrencyMap()
    {

        Map(x => x.id); // Optional
        KeyColumn(x => x.code)


        Map(x => x.name);
        Map(x => x.shname);
        Map(x => x.symbol);
        Map(x => x.deleted);
        HasMany(x => x.Losings).Cascade.All();
        Table("currency");
    }
}

According to the FluentNHibernate "HasMany / one-to-many" documentation, "As with References, the foreign-key defaults to Author_id, and you can override it with the KeyColumn method or change the default behaviour with a Conventions.", so you can also use:

HasMany(x => x.Losings).KeyColumn(x => x. CurrencyCode).Cascade.All();
like image 55
r.pedrosa Avatar answered Sep 17 '22 07:09

r.pedrosa