B
B
Barabasishe2014-04-24 09:18:28
NHibernate
Barabasishe, 2014-04-24 09:18:28

How to insert new record into table with composite key using fluent nhibernate?

Good day to all.
I have a Person entity.
I have the entity Program.
Each Person can have multiple Programs and each Program can have multiple Persons.
There is an entity PersonProgram.
Using Fluent NHibernate I create classes like this:

// Person
    public class Person : Entity
    {        
        public virtual Int32 Id { get; set; }
        public virtual IList<PersonProgram> Programs { get; set; }
        ...
    }
    public class PersonMap : ClassMap<Person>
    {        
        Table("Person");
        Id(p => p.Id).Column("Id");
        HasMany(p => p.Programs).KeyColumn("personID").Inverse();
        ...
    }
 
// Program
    public class Program : Entity
    {        
        public virtual Int32 Id { get; set; }
        ...
    }
    public class ProgramMap : ClassMap<Program>
    {        
        Table("Program");
        Id(p => p.Id).Column("Id");
        ...
    }
// PersonProgram
    public class PersonProgram : Entity
    {        
        public virtual Person person { get; set; }
        public virtual Program Program { get; set; }
        ...
    }
    public class PersonProgramMap : ClassMap<PersonProgram >
    {        
        Table("PersonProgram");
        CompositeId()
                .KeyReference(p => p.Person, "personID")
                .KeyReference(p => p.Program, "programID");
        ...
    }

I receive the data, everything is fine with this.
When creating a new PersonProgram instance and saving it to the database, an error pops up.
var newPersonProgram = new PersonProgram();
    
    newPersonProgram.Person = existedPerson;
    newPersonProgram.Program = existedProgram;
    ...
    using (ITransaction transaction = _session.BeginTransaction())
    {        
        _session.SaveOrUpdate(newPersonProgram); // -- ошибка, что countRow = 2, ожидается 1
        //_session.Save(newPersonProgram); -- ошибка, что countRow = 2, ожидается 1
        //_session.Merge(newPersonProgram); -- ошибка, что поле personID не может быть заполнено значением NULL
 
       transaction.Commit();
    }

On Commit, exceptions pop up that are given in the comments to each save function.
What am I doing wrong?
I understand that NHibernate is trying to generate an id, although it is already in the corresponding records, it remains only to insert them. How to be?

Answer the question

In order to leave comments, you need to log in

Similar questions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question