我有以下类(class):
public class Product
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual Decimal PricePerMonth { get; set; }
public virtual BillingInterval DefaultBillingInterval { get; set; }
public virtual string AdditionalInfo { get; set; }
}
映射看起来像这样:
<class name="Product" table="Products">
<id name="Id" column="ProductId">
<generator class="guid.comb"/>
</id>
<property name="Name" column="ProductName" not-null="true" type="String" />
<property name="PricePerMonth" column="PricePerMonth" not-null="true" type="Decimal" />
<property name="DefaultBillingInterval" type="int" not-null="true" />
<property name="AdditionalInfo" type="string" not-null="false" />
</class>
我使用 Repository<T>
具有以下方法的类(Session
是返回当前 session 的属性):
public IEnumerable<T> FindAll(DetachedCriteria criteria)
{
return criteria.GetExecutableCriteria(Session).List<T>();
}
现在,当我执行以下操作时( session 与存储库中使用的 session 相同):
IEnumerable<ProductDTO> productDTOs = null;
using(ITransaction tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
{
var products = repository.FindAll(new DetachedCriteria.For<Product>().Add(Restrictions.Like("Name", "Some Product%")));
productDTOs = ToDTOs(products);
tx.Commit();
}
// Do stuff with DTO's
commit 语句在那里,因为我使用了一个服务层,如果没有发生错误,它会自动提交每个事务。我只是在这里折叠了我的服务层以便于可视化..
我的 ToDTOs
方法简单地转换为 DTO:
private IEnumerable<ProductDTO> ToDTO(IEnumerable<Product> products)
{
return products.Select(x => new ProductDTO()
{
Id = x.Id,
Name = x.Name,
PricePerMonth = x.PricePerMonth,
AdditionalInfo = x.AdditionalInfo
}).ToList();
}
我的 nhibernate 日志显示以下输出:
2010-01-04 19:13:11,140 [4] DEBUG NHibernate.SQL - SELECT ... From Products ...
2010-01-04 19:13:11,237 [4] DEBUG NHibernate.SQL - UPDATE Products ...
2010-01-04 19:13:11,548 [4] DEBUG NHibernate.SQL - UPDATE Products ...
...
因此,通过选择产品,它会为 session 提交时返回的每个产品发出更新语句,即使产品中没有任何更改。
有什么想法吗?
最佳答案
只有当我有一个实体从属性返回的值与分配给它的值不同时,我才会产生这种效果。然后它被 NH 视为脏。
例子:
class Foo
{
private string name;
public string Name
{
// does not return null when null had been set
get { return name ?? "No Name"; }
set { name = value; }
}
}
这就是我编写映射文件的方式。
<class name="Product" table="Products">
<id name="Id" column="ProductId">
<generator class="guid.comb"/>
</id>
<property name="Name" column="ProductName" not-null="true" />
<property name="PricePerMonth" not-null="true" />
<property name="DefaultBillingInterval" not-null="true" />
<property name="AdditionalInfo" />
</class>
您不需要指定类型。它们由 NHibernate 在运行时确定。
关于c# - Nhibernate 在选择时做更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2001297/