【问题标题】:Object Refrence Error in MySQL + Entity frameworkMySQL + Entity 框架中的对象引用错误
【发布时间】: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=&quot;server=localhost;User Id=root;password=root;database=entityframework&quot;" providerName="System.Data.EntityClient" />

请帮帮我,我哪里出错了?

谢谢!

【问题讨论】:

  • 你能粘贴 entityframeworkEntities() 的定义吗
  • .edmx的构造函数。它没有定义。
  • 尝试使用不同的连接字符串名称,因为类名和连接字符串名称相同会​​让人感到困惑。虽然两者都有不同的类型,但应该不是问题,但减少此类因素以找到问题。
  • 但名称不会导致问题。

标签: c# asp.net mysql entity-framework


【解决方案1】:

您可能忽略了几件事。没有那么多答案。很长的时间才能发表评论

<system.data>
    <DbProviderFactories>
        <remove invariant="MySql.Data.MySqlClient" />
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>

a.build clean.

b.build mysql dll到你的bin目录

c.为 MySQL.Data 和 MySQL.Data.Entities 安装 nuget 包。((右键单击程序集并确保在构建之前将 Copy Local 设置为 true)

d.Remove Version=6.3.5.0 标记,并在没有任何版本控制的情况下构建 VS.type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" 而不是指定完整的版本数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-09
    • 2017-06-18
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多