问题
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
回答1:
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="
data source=(LocalDB)\v11.0;attachdbfilename=E:\Projects\WPF\EntityFrameworkCRUDDataGridWPF\EntityFrameworkCRUDDataGridWPF\AppData\EmployeeDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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.
回答2:
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; }
}
回答3:
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); } }
来源:https://stackoverflow.com/questions/39552207/entityframework-6-0-0-0-reads-data-but-it-is-not-inserting