nHibernate 2.1:在 for 中保存一个新实体
好吧,这让我发疯,我不明白为什么会发生这种情况。 我有一种保存工作经验列表的方法,并且工作经验与公司有关系。问题来了,我试图在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来这之间的关系目前是强制性的,您有两个基本选择:
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