我有以下课程:
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是返回当前会话的属性):
public IEnumerable<T> FindAll(DetachedCriteria criteria) { return criteria.GetExecutableCriteria(Session).List<T>(); }
现在,当我执行以下操作时(会话与存储库中使用的会话相同):
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(); }
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 ... ...
因此,通过选择产品,它会为会话提交时返回的每个产品发出更新声明,即使产品中没有任何更改.
有任何想法吗?
解决方法
当我有一个实体没有从属性返回相同的值而不是分配给它的值时,我只有这种效果.然后它被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在运行时确定.