我在数据实体项目中使用EF4,还有另一个商业实体项目。
我使用显式运算符将Data实体对象转换为Business对象,第一个类是Order,第二个类是SalesChannel
[DataContract]
public class Order
{
[DataMember]
public Guid OrderID { get; set; }
[DataMember]
public SalesChannel SalesChannel { get; set; }
public static explicit operator Order(Data.Entities.Order orderEntity)
{
return new Order()
{
OrderID = orderEntity.OrderID,
SalesChannel = **(SalesChannel)orderEntity.SalesChannel**
};
}
和
[DataContract]
public class SalesChannel
{
[DataMember]
public Guid SalesChannelID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string Description { get; set; }
public static explicit operator SalesChannel(Data.Entities.SalesChannel salesChannelEntity)
{
return new SalesChannel()
{
SalesChannelID = salesChannelEntity.SalesChannelID,
Name = salesChannelEntity.Name,
Email = salesChannelEntity.Email,
Description = salesChannelEntity.Description
};
}
}
但是,在转换SalesChannel对象时,我收到此错误:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我认为在SalesChannel类中没有正确投射。
using (var orderDataProvider = new OrderDataProvider())
{
var orderList = orderDataProvider.GetAllOrders();
orders.AddRange(orderList.Select(order => (Order) order));
}
答案 0 :(得分:0)
这里的问题是延迟执行。更改正在执行AddRange
的内部语句,以输出List<T>
,这将强制执行查询。不久前我在某些代码中遇到了同样的问题。
orderList.Select(order => (Order) order).ToList();
将它包装在using
中,你做得很好。但是,因为你是谨慎的,你也看到了延期执行的影响。
基于问题实际上是获取SalesChannel
的事实,请确保在该类型上发出Include
,以便立即加载而不是延迟加载。