【发布时间】:2013-01-30 06:32:50
【问题描述】:
我正在尝试使用 MySql 数据库学习实体框架。
尝试使用以下代码保存数据:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text == string.Empty ||
txtAge.Text == string.Empty)
{
lblMsg.Text = "Please enter proper details first";
return;
}
employee emp = new employee();
emp.Name = txtName.Text;
emp.Age = Convert.ToInt32(txtAge.Text);
using (entityframeworkEntities context =
new entityframeworkEntities())
{
context.AddToemployees(emp);
if (context.SaveChanges() == 1) // Error Part
{
lblMsg.Text = "Saved Successfully.";
}
}
}
代码在 if (context.SaveChanges() == 1) 上出现 Object Reference 错误。甚至emp 也没有添加到contaxt 对象中。
当我调试代码时,调试器会转到以下部分:
public entityframeworkEntities() :
base("name=entityframeworkEntities", "entityframeworkEntities")
{
this.OnContextCreated();
}
即使在这部分,调试器也会使用大括号,但会跳过 this.OnContextCreated(); 行。
这是我在 Web.Config 中的连接字符串
<add name="entityframeworkEntities" connectionString="metadata=res://*/ApplicationWithMySql.csdl|res://*/ApplicationWithMySql.ssdl|res://*/ApplicationWithMySql.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;User Id=root;password=root;database=entityframework"" providerName="System.Data.EntityClient" />
请帮帮我,我哪里出错了?
谢谢!
【问题讨论】:
-
你能粘贴 entityframeworkEntities() 的定义吗
-
是
.edmx的构造函数。它没有定义。 -
尝试使用不同的连接字符串名称,因为类名和连接字符串名称相同会让人感到困惑。虽然两者都有不同的类型,但应该不是问题,但减少此类因素以找到问题。
-
但名称不会导致问题。
标签: c# asp.net mysql entity-framework