NHibernate:多对一 - *您必须*加载父对象?

标签 nhibernate loading internals object-persistence

假设有以下实体类:

public class Player
{
 public virtual int ID { get; set; }
 public virtual string Name { get; set; }
 public virtual Team Team { get; set; }
}

public class Team
{
 public virtual int ID { get; set; }
 public virtual string City { get; set; }
 public virtual string Nickname { get; set; }
}

假设 Player 有以下映射类:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
 <class name="Player">
  <id name="ID" column="ID" type="System.Int32" unsaved-value="null">
   <generator class="native"/>
  </id>
  <property name="Name" column="Name" not-null="true" type="System.String"  length="50" insert="true" update="true"/>
  <many-to-one name="Team" not-null="true" outer-join="auto" insert="true" update="true">
   <column name="TeamID"/>
  </many-to-one>
 </class>
</hibernate-mapping>

并假设以下 Player 存储库方法:
public void Add(Player player)
{
 using (ISession session = NHibernateHelper.OpenSession())
 {
  using (ITransaction transaction = session.BeginTransaction())
  {
   session.Save(player);
   transaction.Commit();
  }
 }
}

我的问题:

当我想创建一个新玩家时,我必须加载一个完整的团队(父对象)吗?
或者我可以指定一个“模拟”对象,并且只指定外键?
Player player = new Player
              {
               Name = "Tom Brady",
               Team = new TeamRepository().GetTeamByCityAndNickname("New England", "Patriots") // Is this the only way?
               // or can I do this?
               // Team = new Team { ID = 22 }
              };
new PlayerRepository().Add(player);

  • 如果我不能指定一个“模拟”
    对象(仅指定
    外键),你能解释一下吗
    为什么我不能?
  • 也就是说,你能给我一个关于引擎盖下发生了什么的想法吗?


  • 当心:
  • 一个老乡有nearly the same question .
  • 这是the answer that made the most sense .


  • 有趣的是,当谈到 EF
    4.0 期间 DotNetRocks episode , Julia ·勒曼
    承认很多人都想
    在这些类型中使用外键
    情况。


  • 编辑: This answer指出了我问题的本质。

    Think of it like having an object that only keeps the Id and that will load the rest if you ever need it. If you're just passing it arround to create relationships (like FKs), the id is all you'll ever need.


  • 好吧,如果是这样,那为什么我需要担心代理对象之类的?如果这真的很重要,为什么我不能创建一个“虚拟”对象并指定外键值?
  • 最佳答案

    你像这样使用外键......

    Team = session.Load<Team>(id);
    

    知乎 difference between load and get

    关于NHibernate:多对一 - *您必须*加载父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158045/

    相关文章:

    c# - NHibernate 中 Session.Merge 方法的用法是什么?

    c# - Nhibernate QueryOver - 获取分页的子计数

    jquery - 创建过渡时显示加载消息

    c++ - 列出所有打开的文件

    mysql - 插入多行时出现 NonUniqueObjectException 错误,LAST_INSERT_ID() 返回 0

    java - 在Java中实例化大量子类的最有效方法?

    php - jquery 时事通讯提交 - 加载消息

    python - 绑定(bind)调用中发生了什么? (Python+套接字+strace)

    r - R 中的因素 : more than an annoyance?

    asp.net-mvc - NHibernate.Validator 与 DataAnnotations