简体   繁体   English

使用NHibernate插入或保存时为Object Proxies提供什么值

[英]What value to give for Object Proxies when Inserting or Saving using NHibernate

Let us assume that we have Class TableChild and Class TableParent. 我们假设我们有Class TableChild和Class TableParent。 They correspond to similar tables in the database. 它们对应于数据库中的类似表。 TableChild and TableParent have a relationship as indicated by their names. TableChild和TableParent具有由其名称指示的关系。 TableChild class has a property of type TableParent to replicate the relationship in our classes. TableChild类有一个TableParent类型的属性来复制我们类中的关系。 Now when I am inserting a new object for TableChild, how do we provide the value for the property of TableParent. 现在,当我为TableChild插入一个新对象时,我们如何为TableParent的属性提供值。 Should we just assign the ID of TableParent to the TestChild. 我们应该只将TableParent的ID分配给TestChild。 Or do we fetch the whole object from the DB using the ID value of TableParent and then assign this object to the TableChild. 或者我们使用TableParent的ID值从DB获取整个对象,然后将此对象分配给TableChild。 The second method is feasible but would bring more performance overhead as we have to issue extra Select statements. 第二种方法是可行的,但由于我们必须发出额外的Select语句,因此会带来更多的性能开销。

The mapping that we are using is the simple Please do suggest some easy methods, if possible, to store the relationship to the child table while inserting new values for the same. 我们使用的映射很简单。如果可能,请建议一些简单的方法,以便在为子表插入新值时将关系存储到子表中。

In C#, the relationships are object references. 在C#中,关系是对象引用。

public class TableParent
{
}

public class TableChild
{
    TableParent Parent { get; set; }
}

To create a child with a known parent, give it a parent object that is known to NHibernate. 要创建具有已知父级的子级,请为其提供NHibernate已知的父对象。 Using ISession.Load() gives a proxy object without touching the database (assuming lazy loading has not been disabled). 使用ISession.Load()在不触及数据库的情况下提供代理对象(假设尚未禁用延迟加载)。

// create and save a child with a known parent
var c = new TableChild {
    Parent = session.Load<TableParent>( parent_id );
};
session.Save( c );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM