简体   繁体   中英

Using the same model for two different repository in NHibernate

I have a model class like this,

 Class Student
{
    private virtual int StudentId;  --> id column
    private virtual int StudentName;
}

I have two repositories say LabRepository & LibraryRepository both of which has a table for Student.

Problem: When i try to retrieve the Student object from LabRepository and use the same model to insert into LibraryRepository, it fails because the StudentId value is 1 when retireved from LabRepository and NHibernate will execute a Update query instead of Insert query when it sees the Id column as 1.The Update query fails because there is no Student record with ID as 1 in Library

I have just given a sample here, but my actual model class is even complex with many id columns composed inside it.Is there any way by which I take a model object from one repository and insert the same into other repository without worrying on the id columns?

it could be done when mapping Student twice with a explicitly stated EntityName other than the class name

change the idgeneration to assigned and map the reference

public LibraryStudentMap()
{
    EntityName("LibraryStudent");
    Table("LibraryStudents");

    Id(x => x.StudentId).GeneratedBy.Assigned();
}
public LabStudentMap()
{
    EntityName("LabStudent");
    Table("LabStudents");

    Id(x => x.StudentId).GeneratedBy.Assigned();
}

public LibraryMap()
{
    References(x => x.Student).EntityName("LibraryStudent");
}

public LabMap()
{
    References(x => x.Student).EntityName("LabStudent");
}

then it should be possible to

lab.Student = library.Student;
session.SaveOrUpdate(lab);

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