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