Maintain referential integrity when pasting with NHibernate

I thought a lot about nhibernate, but this seems to be my last hurdle, not understanding what is going on. So here is the problem.

I have a basic database structure:

Shows:
ID [Pk]
CountryID [Fk]
Name

Countries:
ID [Pk]
Name

CountryID has a foriegn key link from readings to the primary key of the country table, and countries are already filled with preset values ​​that rarely change.

Here are my mapping files

    public ShowMap()
    {
        Table("Shows");

        Id(x => x.ID);
        Map(x => x.Name)

        HasOne<Country>(x => x.CountryOrigin)
            .Cascade.All()
            .ForeignKey("CountryID");
    }

    public CountryMap()
    {
        Table("Countries");

        Id(x => x.ID);
        Map(x => x.Name);
    }

I am pretty sure that this is a display problem, but when I do an insert in the show and I have a country attached to it. He is trying to insert a new country into the database, rather than using an existing one in the database. Which, apparently, is the main problem. I do not know how to correctly insert a tab where it uses an existing entry in the database.

, , , , .

        using (var tx = _session.BeginTransaction())
        {

            Show s1 = new Show();
            s1.CountryOrigin = new Country { ID = 2, Name = "Japan" };
            s1.Name = "Liar Game";

            _session.SaveOrUpdateCopy(s1);
            tx.Commit();
            tx.Dispose();
            return true;
        }

, , ?


1. , , , , , . , . .

:

        using (var tx = _session.BeginTransaction())
        {

            Show s1 = new Show();
            s1.CountryOrigin.Add(_session.Get<Country>(2));
            s1.Name = "Liar Game";

            _session.SaveOrUpdateCopy(s1);
            tx.Commit();
            return true;
        }

:

    public ShowMap()
    {
        Table("Shows");

        Id(x => x.ID);
        Map(x => x.Name)

        HasMany<Country>(x => x.CountryOrigin)
            .KeyColumn("ID")
            .Cascade.SaveUpdate();
    }

    public CountryMap()
    {
        Table("Countries");

        Id(x => x.ID);
        Map(x => x.Name);
    }

- null CountryID, .

2 /:

            s1.CountryOrigin.Add(_session.Get<Country>(2));

, , , . , , .

+3
2

" " . ​​ References:

public ShowMap()
{
    Table("Shows");

    Id(x => x.ID);
    Map(x => x.Name)

    References(x => x.CountryOrigin, "CountryID");
}
+3

Session.Load Country:

s1.CountryOrigin = _session.Load<Country>(2);

Session.Load : " , db . , , ". Session.Get, db.

0

Source: https://habr.com/ru/post/1751248/


All Articles