C# System.InvalidCastException:尝试在C中使用实体框架向SQL数据库添加对象时#
我正在尝试使用C#中的实体框架向SQL数据库添加对象。数据来自文本框和日期选择器控件的组合。我猜这是我如何解析数据的一个问题,但是错误对我来说似乎很模糊。如有任何建议,将不胜感激 下面是将数据添加到数据库的代码C# System.InvalidCastException:尝试在C中使用实体框架向SQL数据库添加对象时#,c#,sql,database,parsing,ado,C#,Sql,Database,Parsing,Ado,我正在尝试使用C#中的实体框架向SQL数据库添加对象。数据来自文本框和日期选择器控件的组合。我猜这是我如何解析数据的一个问题,但是错误对我来说似乎很模糊。如有任何建议,将不胜感激 下面是将数据添加到数据库的代码 private void new_btn_Click(object sender, RoutedEventArgs e) { var load = new Load { pro_num = pro_txt.Text,
private void new_btn_Click(object sender, RoutedEventArgs e)
{
var load = new Load
{
pro_num = pro_txt.Text,
quote_num = quote_txt.Text,
ref_num = ref_txt.Text,
weight = Convert.ToDouble(weight_txt.Text),
pieces = Convert.ToInt32(pieces_txt.Text),
commodity = commodity_txt.Text,
mileage = Convert.ToDouble(mileage_txt.Text),
carrier_rate = Convert.ToDecimal(carrierRate_txt.Text),
customer_rate = Convert.ToDecimal(customerRate_txt.Text),
pick_appointment = pickDate_picker.SelectedDate,
drop_appointment = dropDate_picker.SelectedDate,
driver_id = Convert.ToInt32(driver_txt),
dispatch_id = Convert.ToInt32(dispatch_txt),
customer_id = Convert.ToInt32(customer_txt),
broker_id = Convert.ToInt32(broker_txt),
};
HotloadModel.Loads.Add(load);
HotloadModel.SaveChangesAsync();
}
以下是EF实体类的代码:
public partial class Load
{
public int bol_num { get; set; }
public string pro_num { get; set; }
public string quote_num { get; set; }
public string ref_num { get; set; }
public Nullable<double> weight { get; set; }
public Nullable<int> pieces { get; set; }
public string commodity { get; set; }
public Nullable<double> mileage { get; set; }
public Nullable<decimal> carrier_rate { get; set; }
public Nullable<decimal> customer_rate { get; set; }
public Nullable<System.DateTime> pick_appointment { get; set; }
public Nullable<System.DateTime> drop_appointment { get; set; }
public Nullable<int> driver_id { get; set; }
public Nullable<int> dispatch_id { get; set; }
public Nullable<int> customer_id { get; set; }
public Nullable<int> broker_id { get; set; }
}
在盯着代码看了15分钟后,我意识到我忽略了在这些行中指定.Text属性
driver_id = Convert.ToInt32(driver_txt),
dispatch_id = Convert.ToInt32(dispatch_txt),
customer_id = Convert.ToInt32(customer_txt),
broker_id = Convert.ToInt32(broker_txt),
此外,我还使用了一篇相关SO帖子中的链接来验证我是否正确转换了值 我认为这些字段也在文本框中,也许您必须获得文本值:
driver_id = Convert.ToInt32(driver_txt.Text),
dispatch_id = Convert.ToInt32(dispatch_txt.Text),
customer_id = Convert.ToInt32(customer_txt.Text),
broker_id = Convert.ToInt32(broker_txt.Text),
下次阅读异常:“无法将'System.Windows.Forms.TextBox'类型的对象强制转换为'System.IConvertible'类型”否,我获取文本属性,例如:
driver\u txt.text
,因为您在上一条注释中写了一个异常。在您的示例中,您尝试从driver\u txt
而不是driver\u txt.Text
获取int32值。