3

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
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • Can you send Department table schema ? Did you set a primary key in the table ? [DatabaseGenerated(DatabaseGeneratedOption.Identity)] – Hüseyin Burak Karadag Sep 17 '16 at 22:20
  • What is the SQL query EF is generating when you run the `Add`? Check `Immediate Window` in VS. – L J Sep 17 '16 at 22:20
  • @HüseyinBurakKaradag please, see updated section of my question – StepUp Sep 17 '16 at 22:23
  • If you can get the query from your IDE (http://stackoverflow.com/a/20751723/6830901) and run it against your DB it would be useful. – L J Sep 17 '16 at 22:27
  • @LJ please, see my updated question with what SQL query is run and its result. – StepUp Sep 17 '16 at 22:35
  • We might need to tell the `EF` that the context is modified. Could you please try with - `EntityState.Modified` on the entity state? – L J Sep 17 '16 at 22:52
  • @LJ nothing added. I've updated my question about what I've tried. – StepUp Sep 17 '16 at 23:06
  • Can we try `Attach` ; `db.Departament.Attach(dep)` as we are inserting a new entry; Apologies for keeping you long as it is taking time to understand the underlying logic. – L J Sep 17 '16 at 23:23
  • @LJ it is okay:). But `db.Departament.Attach(dep);` is not inserting data. – StepUp Sep 17 '16 at 23:28
  • It will attach to the object and on `SaveChanges` it should be reflected on the DB. Is it not? – L J Sep 17 '16 at 23:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123614/discussion-between-stepup-and-l-j). – StepUp Sep 17 '16 at 23:33
  • Departament class is partial. What are the other declarations of this class? – DevilSuichiro Sep 18 '16 at 04:29

3 Answers3

3

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.

StepUp
  • 36,391
  • 15
  • 88
  • 148
1

Set IdDep column [Key] and [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attributes

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; }
}
  • thanks, I've tried to do this, but it does not help. No new data is added to `Department` table. – StepUp Sep 17 '16 at 22:36
1

The code looks fine; only thing which I think to be looked up for are:

  • The connection string (Make sure that the entity being updated are in the correct database; since you are using LocalDB, ping against that particular database table using Server Explorer
  • Please also take a look at this answer - https://stackoverflow.com/a/26343750/6830901 and update your connection string based on the SQL Server you are targeting at.
  • The code below should work if no EF exceptions are thrown (based on points above)

        using (PersonDBEntities db = new PersonDBEntities())
        {
            try
            {
                Departament dep = new Departament() { DepName = "New Department" };
                db.Departament.Add(dep);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
    
Community
  • 1
  • 1
L J
  • 5,249
  • 3
  • 19
  • 29