问题
At first I should mention that this problem only occurs in windows forms applications and the same program in web mode for example with MVC3 works perfect.
Some days ago I wrote a very simple windows form program using Visual studio 2010 ultimate with a SQL Express database. I added the database by choosing Add > New item > Service-Based database and an entity data model based on this database in same way. I used Entity framework for adding some new records to tables. I had done such thing with VS 2008 SP1 before with no problem so I did the same. The program compiled and ran with no errors and I entered some new data. after exiting the program I came back to the database and nothing was happened. None of information I had entered had been saved. I debug the program step by step and everything was alright. The code below is related to a very simple program with mentioned problem. Database has one table (book):
namespace Book
{
public partial class BookForm : Form
{
BookDatabaseEntities db = new BookDatabaseEntities();
public BookForm()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
Book bookToCreate = new Book();
bookToCreate.Id = Guid.NewGuid();
bookToCreate.Title = titleTextBox.Text;
db.Books.AddObject(bookToCreate);
db.SaveChanges();
}
}
}
I'll be very grateful if anyone help me. Thanks in advance.
.................
After editing:
namespace Book
{
public partial class BookForm : Form
{
//BookDatabaseEntities db = new BookDatabaseEntities();
public BookForm()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
var db = new BookDatabaseEntities();
var bookToCreate = db.Books.CreateObject();
//Book bookToCreate = new Book();
bookToCreate.Id = Guid.NewGuid();
bookToCreate.Title = titleTextBox.Text;
db.AcceptAllChanges();
db.Books.AddObject(bookToCreate);
db.SaveChanges();
}
}
}
回答1:
Finally after lots of searching and asking I found the solution in MSDN forums thanks to Patrice Scribe You can see it here
回答2:
try this:
db.Attach(bookToCreate);
db.SaveChanges();
Edit:
I have this code in a class library (my DAL) in production and it works fine:
using (var dbContext = new DbEntities())
{
var job = dbContext.RiskToolJob.CreateObject();
job.AnalysisDataID = analysisDataID;
job.JobRmsAnalysisID = RMSAnalysisID;
job.UserName = userName;
job.JobCreated = DateTime.UtcNow;
dbContext.RiskToolJob.AddObject(job);
dbContext.SaveChanges();
return job.DataId;
}
notice that in fact I do not assign the PK (DataId) because it will be assigned by the database, i return it to the caller so who has invoked the save method gets to know the auto generated ID, in case it needs it.
来源:https://stackoverflow.com/questions/7329167/entity-framework-doesnt-save-data-entries-in-database