c# - "The given key was not present in the dictionary"nHibernate C#

标签 c# nhibernate

我是 nHibernate 的新手。我在两个表“User”和“UserProfile”之间设置了以下一对一映射。

用户.hbm.xml:

 <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"           namespace="Core.Domain.Model" assembly="Core">

  <class name="User" table="Users" dynamic-update="true" lazy="false">
    <cache usage="read-write"/>
    <id name="UserId" column="UserId" type="guid">
    </id>
    <one-to-one name="UserProfile" class="UserProfile"/>
  </class>
</hibernate-mapping>

用户配置文件.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Core.Domain.Model" assembly="Core">
<class name="UserProfile" table="UserProfiles" dynamic-update="true" lazy="false">
    <cache usage="read-write"/>
    <id name="UserProfileId" column="UserProfileId" type="int">
      <generator class="native"/>
    </id>
    <property name="Description" length="100"/>
  <many-to-one name="User" unique="true" column="UserId"/>
  </class>
</hibernate-mapping> 

我对上述映射的 POCO 是:

public class User
    {
        public virtual Guid UserId { get; set; }
        public virtual UserProfile UserProfile { get; set; }

    }

public class UserProfile
    {
        public virtual int UserProfileId { get; set; }
        public virtual User User { get; set; }
    }

现在,当我尝试保留我的“用户”对象时,出现异常: “字典中不存在给定的键”:

using (ISession session = SessionFactory.OpenSession())

有人知道这里会发生什么吗?

最佳答案

我将您的 hbm 映射和类复制到我的测试项目中。创建 SessionFactory 时出现错误。您是否有机会在使用语句中首次访问 SessionFactory 时创建它?如果是这样,那么这将有望解决问题:

我通过添加修复了它

public virtual String Description { get; set; }

到 UserProfile 类。 如果您的代码中有它,只是在复制和粘贴过程中忘记了它,我会尝试进一步调查。

编辑:

此错误的另一个可能来源 - 发现 here :

请确认您所有的 .hbm.xml 文件都是嵌入式资源。

如果仍然没有帮助,您能否发布异常的 StackTrace?

关于c# - "The given key was not present in the dictionary"nHibernate C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303322/

相关文章:

c# - 正则表达式同时向前看和向后看

c# - 如何限制 NHibernate 的 GetByCriteria 拉回的结果集?

unit-testing - 用于测试的 NHibernate Load 与 Get 行为

c# - 扩展 Asp.Net Identity IsInRole() 方法

c# - 计算 WPF 或 SVG 图形的坐标点

c# - 如何限制用户在 TextBox 中输入的值?

c# - 如何在删除之前显示加载 gif?

nhibernate - Linq to Nhibernate - Select 中的调用方法破坏了 IQueryable

NHibernate 集合加载, "illegal access to loading collection"

c# - LINQ 计算链接表中的行数