简体   繁体   English

实体框架:调用保存更改时出错

[英]Entity framework: error in calling save changes

I am working with entity framework to connect MySql. 我正在使用实体框架来连接MySql。 I have created a entity data modal with the MySql database, it generate the connection string in web.config automatically which is as follows in my case:- 我已经使用MySql数据库创建了一个实体数据模态,它会在web.config中自动生成连接字符串,在我的情况下如下:

 <add name="entityframework1" connectionString="metadata=res://*/EntityFramework.csdl|res://*/EntityFramework.ssdl|res://*/EntityFramework.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=localhost;User Id=root;database=entityframework&quot;" providerName="System.Data.EntityClient" />

Now I want to save record in database and the code is as follows:- 现在我想将记录保存在数据库中,代码如下:-

        employee emp = new employee();
        emp.Name = txtName.Text;
        emp.Age = Convert.ToInt32(txtAge.Text);

        using (entityframework context =
              new entityframework())
        {

            context.AddToemployees(emp);
            if (context.SaveChanges() == 1)
            {
                lblMsg.Text = "Saved Successfully.";
            }
        }

it gives error 它给出了错误

"object reference not set to an instance of object" on the if condition having "context.SaveChanges". 如果条件为“ context.SaveChanges”,则“对象引用未设置为对象实例”。

I also tried to pass the connection string at the time of creating context 我还尝试在创建上下文时传递连接字符串

string connectionstring = "SERVER=localhost;DATABASE= entityframework ;UID= root;";

but it gives error that "Keyword not supported: '"server'." this is my first effort in entity framework, is there anybody to advise me. 但这会出现错误,提示“不支持关键字:'“服务器'。”这是我在实体框架中的首次尝试,有人建议我。

If you can retrieve data from the server then the connection string is good. 如果可以从服务器检索数据,则连接字符串很好。

As for the SaveChanges() try calling context.ChangeTracker.DetectChanges() first and as a success condition you can set the initial id of the entity to -1 for instance and afterwards check if it is >= 0. (That is, if your PrimaryKey is also Autoincrement/Identity) 至于SaveChanges(),请尝试首先调用context.ChangeTracker.DetectChanges() ,作为成功条件,您可以将实体的初始ID例如设置为-1,然后检查其是否大于等于0。(即,是否您的PrimaryKey也是自动递增/身份)

You need to also add the following to your web.config file (replace the Version string with the appropriate version of your MySQL .NET connector) 您还需要将以下内容添加到web.config文件中(用适当的MySQL .NET连接器版本替换Version字符串)

<system.data><DbProviderFactories>
  <clear />
  <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.6.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories></system.data>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM