我使用LinqToSql作为ORM。我有一个包含以下代码的表单:
public partial class frmBarcodeList : Form
{
private ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["myconn"];
private DatabaseContext _context;
public frmBarcodeList()
{
_context = new DatabaseContext(connectionString.ConnectionString);
InitializeComponent();
}
}
在按钮处理程序中,点击我拨打GetInfoFromDataBase
。
这是问题方法:
private List<TicketInfo> GetInfoFromDataBase()
{
try
{
var oids = GetSelectedEvents();
List<Order> orders = new List<Order>();
List<TicketInfo> data = new List<TicketInfo>();
foreach (var oid in oids)
{
orders.AddRange(_context.Orders.Where(o => o.ScheduleId == oid && o.IsPayed.Value).ToList());
}
foreach (var order in orders)
{
foreach (var detail in order.OrderDetails) ***line 158**
{
var checkSum = CalculateChecksum(detail.BarCode);
TicketInfo info = new TicketInfo();
info.Firstname = order.SiteUser.FirstName;
info.LastName = order.SiteUser.LastName;
info.Email = order.SiteUser.Email;
info.Phone = order.SiteUser.PhoneNumber;
info.Barcode = string.Format("{0}{1}", detail.BarCode, checkSum);
info.FileName = RemoveInvalidFilePathCharacters(string.Format("{0}_{1}", order.EventSchedule.BaseEvent.Name,
order.EventSchedule.RecurrenceStart), "");
data.Add(info);
}
}
return data;
}
catch (Exception e)
{
MessageBox.Show(e.Message + "\n" + e.StackTrace);
}
return null;
}
我收到错误:
---------------------------
---------------------------
Specified cast is not valid.
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at Read_OrderDetail(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Data.Linq.EntitySet`1.Load()
at System.Data.Linq.EntitySet`1.GetEnumerator()
at DT.KazBilet2.BarcodeChecker.frmBarcodeList.GetInfoFromDataBase() in C:\Users\Макс\Documents\Visual Studio 2010\Projects\DT.KazBilet2\branches\NewDesk\DT.KazBilet2.BarcodeChecker\frmBarcodeList.cs:line 158
---------------------------
ОК
---------------------------
为什么我收到此错误?
感谢。
答案 0 :(得分:1)
使用Linq2SQL时,在SqlClient方法中键入强制转换错误(几乎)总是由于模型错误。
我会检查模型是否与数据库一致,尤其是模型中的int字段(get_Int32给出错误)对应于数据库中的实际整数字段。