nHibernate 2.1:在 for 中保存一个新实体

发布于 2024-10-09 04:05:20 字数 841 浏览 0 评论 0原文

好吧,这让我发疯,我不明白为什么会发生这种情况。 我有一种保存工作经验列表的方法,并且工作经验与公司有关系。问题来了,我试图在 foreach 中创建一个新公司并保存它,但 nHibernate 也试图保存 JobExperience ...并且它没有引用 JobExperience!。 这是我的代码:

 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)
        { 

        }
    }

因此,在那一行尝试保存 JobExperience 并且它显示异常,因为它是未保存的。但是,如果我尝试这样做:

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

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

}

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

那行得通!而且它并没有试图保存任何工作经验!....

有什么想法为什么会发生这种情况吗?

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 I-m 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃兔兔 2024-10-16 04:05:20

看起来这之间的关系目前是强制性的,您有两个基本选择:
1)如果在您的系统中,可以在没有公司的情况下获得JobExperience,您可以通过在hbm中说not-null =“true”将关系映射更改为可选(或者在某些流畅的映射工具中进行等效操作,如果您是使用一个)。
2)如果关系是强制性的,你应该先保存一个公司。

HTH,
贝里尔

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文