简体   繁体   中英

nHibernate 2.1: Save a new entity in a for

Well, this is driving me crazy, I cannot understand why is this happening. I have a method for saving a list of JobExperiences and a JobExperience has a relation to a Company. The problem comes that Im trying to create a new Company inside the foreach and save it, but nHibernate is trying to save the JobExperience also ... and it is not referenced to the JobExperience!. Here is my code:

 foreach (JobExperience exp in expList)
 {
    if (exp.Company.IsNew)
    {
        try
        {
            Company c = new Company();
            c.Name = "CompanyTest";

            companyService.Save(c); //throws an exception!
        }
        catch (Exception ex)
        { 

        }
    }

So, at that line is trying to save the JobExperience and it is showing an exception cause it is a non saved one. But, if I try this:

try
{
    Company c = new Company();
    c.Name = "CompanyTest";

    companyService.Save(c);
}
catch (Exception ex)
{

}

foreach (JobExperience exp in expList)
{
//[... code excluded for abbreviation ]

That works!, and it is not trying to save any JobExperience!....

Any thoughts why is this happening?

This looks like the relationship between is currently mandatory, and you have two basic choices:
1) if in your system, it is possible to have JobExperience without a Company, you can just change the relationship mapping to be optional by saying not-null="true in your hbm (or the equivalent in some fluent mapping tool if you are using one).
2) if the relationship should be mandatory, you should save a company first.

HTH,
Berryl

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