>我有一个用于LINQ
扩展方法的类。我从以下班级获得System.TypeInitializationException
:
public static class CarLib {
private readonly static IOPTS_EFEntities Context = new myEFEntities();
public IQueryable<Transmission> GetTransmissions(this Car car, IEFEntities context = null) {
if (context == null)
context = Context;
return SelectCarWithTransmissionCompiled(car, context);
}
public IQueryable<Tire> GetTires(this Car car, IEFEntities context=null) {
if (context == null)
context = Context;
return SelectTiresCompiled(car, context);
}
private static readonly Func<Car, IEFEntities, IQueryable<Transmission>> SelectTransmissionsCompiled = SelectTransmissions.Compile();
private static readonly Func<Car, IEFEntities, IQueryable<Tire>> SelectTiresCompiled = SelectTires.Compile();
private static readonly Expression<Func<Car, IEFEntities, IQueryable<Transmission>>> SelectTransmissions= (myCar,context) =>
from trans in context.Transmissions
where trans.CarId == myCar.Id
select trans;
private static readonly Expression<Func<Car, IEFEntities, IQueryable<Tire>>> SelectTires = (car,context) =>
from tire in context.Tires
where car.Id == tire.CarId
&& accused.Ssn.IsValidSsn()
&& !tire.Brand.IsNullEmptyOrWhitespace()
&& !tire.Diameter.IsNullEmptyOrWhitespace()
&& !tire.Weight.IsNullEmptyOrWhitespace()
&& tire.Price.IsPopulated()
select tire;
}
在单元测试(或只是一个方法)中尝试静态字段(上下文初始化和查询编译)中的代码,并查看实际异常及其堆栈跟踪。
此外,在静态字段中拥有 DataContext 是一个定时炸弹。在每个方法中创建一个新的方法或共享它,将其存储在受控位置(如HttpContext.Item,Call.Context等)