假设有以下实体类:
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);
对象(仅指定
外键),你能解释一下吗
为什么我不能?
当心:
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.
最佳答案
关于NHibernate:多对一 - *您必须*加载父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158045/