让我们假设我有这个类的一个实例。C#在foreach循环中继续处理对象的实例
public class MyClass
{
public string LocationCode;
public string PickUpCode
}
还有另外一个类,需要一个List<MyClass>
作为输入并保存到数据库。
现在我需要办理一些业务规则:
例如,如果LocationCode是null
在List<MyClass>
这个项目必须跳过,foreach
循环必须continue
到列表中的下一个项目。
我已经写了下面的代码,并与null
LocationCode的项目确实是跳过,但因此当循环达到一个有效的项目,并继续将其保存在数据库中var instance = new SomeClass();
莫名其妙地保留在内存中,也保存所有以前跳过的实例var instance = new SomeClass();
。这意味着我在数据库中有空条目。
我正在使用NHibernate和Evict
没有缝隙做的伎俩。有什么建议么?
public void Save(List<MyClass> listOfItems)
{
using (UnitOfWork.Start())
{
var repository = new Repository();
try
{
foreach (var item in listOfItems.Select(i => i.Item).Where(item => item != null))
{
var instance = new SomeClass();
if (pickUpCode != null)
{
instance.PickUpCode = pickUpCode;
}
else
{
instance.PickUpCode = null;
}
if (locationCode != null)
{
instance.StartLocation = locationCode
}
else
{
UnitOfWork.CurrentSession.Evict(instance);
continue;
}
repository.SaveSomeClass(instance);
}
}
catch (Exception ex)
{
_log.Error(" Unhandled error", ex);
}
}
}
**因为有人问,这里的一对UnitOfWork.Start()
public static class UnitOfWork
{
public static IUnitOfWork Start();
}
public interface IUnitOfWork : IDisposable
{
bool IsInActiveTransaction { get; }
IUnitOfWorkFactory SessionFactory { get; }
IGenericTransaction BeginTransaction();
IGenericTransaction BeginTransaction(IsolationLevel isolationLevel);
void Flush();
void TransactionalFlush();
void TransactionalFlush(IsolationLevel isolationLevel);
}
你没有错过'如果检查添加到您LINQ(!item.pickUpCode = NULL)'和' if(item.locationCode!= null)'? – Michael 2014-09-19 07:26:00
这是一个示例代码。实际的更详细。 – 2014-09-19 07:36:05