EntityFramework 6.0.0.0读取数据,但未插入 [英] EntityFramework 6.0.0.0 reads data, but it is not inserting

查看:96
本文介绍了EntityFramework 6.0.0.0读取数据,但未插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将基于服务的数据库 folderName->Add New Item->Data->Service-based Database文件创建到WPF应用程序中.然后,我使用了Database First方法并创建了PersonsModel.edmx文件.这些操作执行得很好.

数据读取正常:

using (PersonDBEntities db = new PersonDBEntities())
{
   string dep = (db.Departament.FirstOrDefault()).DepName;//data can be read perfectly
   string bureau = (db.Bureau.FirstOrDefault()).BureauName;//data can be read perfectly 
}

但是,无法插入数据(此代码在其他项目中也能很好地工作):

using (PersonDBEntities db = new PersonDBEntities())
{
   try 
   {
      Departament dep = new Departament() { DepName = "NewDep" };
      db.Departament.Add(dep);
      db.SaveChanges();
   }
   catch(Exception ex)
   {
      string message = ex.Message;
   }                
 }

有人知道为什么不插入数据吗?

没有错误,异常,只是EF不在写数据.

我已经将项目上传到github ,也许看起来很有趣:)./p>

用于创建表的SQL查询:

CREATE TABLE [dbo].[Departament] (
    [IdDep]   INT            IDENTITY (1, 1) NOT NULL,
    [DepName] NVARCHAR (100) NULL,
    PRIMARY KEY CLUSTERED ([IdDep] ASC)
);

和EF模型类:

public partial class Departament
{
    public Departament()
    {
        this.Person = new HashSet<Person>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int IdDep { get; set; }
    public string DepName { get; set; }

    public virtual ICollection<Person> Person { get; set; }
}

Visual Studio 2013的控制台输出:

从2016年9月18日1开始:34:15 +03:00开始交易

插入[dbo].部门值(@ 0)选择[IdDep]从 [dbo].[部门] @@ ROWCOUNT> 0 AND [IdDep] = scope_identity()

-@ 0:"311"(类型=字符串,大小= 100)

-在18.09.2016 1:34:15 +03:00执行

-在79毫秒内完成,结果为:SqlDataReader

在2016年9月18日的已提交交易1:30:15 +03:00

在18.09.2016 1:34:15 +03:00关闭连接

如果我在Visual Studio 2013中将上述查询作为SQL数据库查询运行,那么它将完美地插入数据.

我已经按顺序尝试了以下方法:

//db.Departament.Add(dep);//not working
//db.Entry(dep).State = EntityState.Added;//not working
//db.Departament.Attach(dep);//not working
//db.Entry(dep).State = dep.IdDep == 0 ? EntityState.Added : EntityState.Modified;//not working
//db.Departament.Attach(dep);//not working
db.Entry(dep).State = EntityState.Modified;//not working

解决方案

一些其他信息:

运行应用程序时(按F5或CTRL + F5组合键),Visual Studio将包括数据库MDF文件在内的所有文件复制到bin文件夹中. 对该文件进行了所有更改数据库复制到bin文件夹.

I've created a Service-based Database folderName->Add New Item->Data->Service-based Database file into WPF application. Then I've used Database First approach and have created the PersonsModel.edmx file. These operations are executed perfectly.

The reading of data works okay:

using (PersonDBEntities db = new PersonDBEntities())
{
   string dep = (db.Departament.FirstOrDefault()).DepName;//data can be read perfectly
   string bureau = (db.Bureau.FirstOrDefault()).BureauName;//data can be read perfectly 
}

However, data can not be inserted(this code works in other projects very well) :

using (PersonDBEntities db = new PersonDBEntities())
{
   try 
   {
      Departament dep = new Departament() { DepName = "NewDep" };
      db.Departament.Add(dep);
      db.SaveChanges();
   }
   catch(Exception ex)
   {
      string message = ex.Message;
   }                
 }

Does anybody know why data is not inserted?

No errors, exceptions, just EF is not writing data.

I've upload a project to github, maybe it can be interesting to see:).

A SQL query to create a table:

CREATE TABLE [dbo].[Departament] (
    [IdDep]   INT            IDENTITY (1, 1) NOT NULL,
    [DepName] NVARCHAR (100) NULL,
    PRIMARY KEY CLUSTERED ([IdDep] ASC)
);

and EF model class:

public partial class Departament
{
    public Departament()
    {
        this.Person = new HashSet<Person>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int IdDep { get; set; }
    public string DepName { get; set; }

    public virtual ICollection<Person> Person { get; set; }
}

What Console of Visual Studio 2013 outputs:

Started transaction at 18.09.2016 1:34:15 +03:00

INSERT [dbo].Departament VALUES (@0) SELECT [IdDep] FROM [dbo].[Departament] WHERE @@ROWCOUNT > 0 AND [IdDep] = scope_identity()

-- @0: '311' (Type = String, Size = 100)

-- Executing at 18.09.2016 1:34:15 +03:00

-- Completed in 79 ms with result: SqlDataReader

Committed transaction at 18.09.2016 1:34:15 +03:00

Closed connection at 18.09.2016 1:34:15 +03:00

If I run the above query as a SQL database query in Visual Studio 2013, then it inserts data perfectly.

I've tried the following approaches in sequential order:

//db.Departament.Add(dep);//not working
//db.Entry(dep).State = EntityState.Added;//not working
//db.Departament.Attach(dep);//not working
//db.Entry(dep).State = dep.IdDep == 0 ? EntityState.Added : EntityState.Modified;//not working
//db.Departament.Attach(dep);//not working
db.Entry(dep).State = EntityState.Modified;//not working

解决方案

Special thanks to Magnus Montin as he has shown the mistake. and I just copy his answer:

But since the INSERT statement is executed and you don't get any exception, how do you confirm that that the data is not inserted? Make sure that you are looking in the right database. That is the database that is located in the output folder of your executable (.exe), typically 'c:\yourprojectfolder\bin\Debug\' or 'c:\yourprojectfolder\bin\Release\'. This is where the data gets written by default.

What I've done to avoid this behaviour is I just write absolute path to my database. Now it looks like that:

<connectionStrings>   
    <add name="PersonDBEntities" connectionString="metadata=res://*/Model.PersonModel.csdl|res://*/Model.PersonModel.ssdl|res://*/Model.PersonModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;
      data source=(LocalDB)\v11.0;attachdbfilename=E:\Projects\WPF\EntityFrameworkCRUDDataGridWPF\EntityFrameworkCRUDDataGridWPF\AppData\EmployeeDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Some additional info:

When you run your application( hit F5 or CTRL+F5 ), Visual Studio copies all of the files including the database MDF file to the bin folder. All changes are made to that database which is copied to bin folder.

这篇关于EntityFramework 6.0.0.0读取数据,但未插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆