简体   繁体   English

nHibernate 2.1:将新实体保存为

[英]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. 我有一种保存JobExperiences列表的方法,而JobExperience与公司有关系。 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!. 问题来了,我试图在foreach中创建一个新公司并保存它,但是nHibernate也在尝试保存JobExperience ...,并且它没有引用到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. 因此,该行正在尝试保存JobExperience,并且显示异常,因为它是未保存的。 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!.... 那行得通!而且它并没有试图保存任何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). 1)如果在您的系统中可以有没有公司的JobExperience,则可以通过在hbm中说出not-null =“ true来更改关系映射为可选(如果您使用的是某些流利的映射工具中的等效项)使用一个)。
2) if the relationship should be mandatory, you should save a company first. 2)如果关系是强制性的,则应首先保存公司。

HTH, HTH,
Berryl 贝里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM