1

I use DataSet to write to the database in my desktop WPF application.

I create one DataSet for one Survey Window that contains several different documents. I add some starting data (add new rows to several tables) then I bind it to the appropriate fields (TextBoxes, CheckBoxes).

Now DataSet has changes, but I can reset them:

dataSet.AcceptChanges();

Than, when a user change something, I can track the changes using:

dataSet.HasChanges();
dataSet.GetChanges();

I would like to transfer the application to Entity Framework.

I found that I could bind to dbContext.MyTable.Local, and check changes by dbContext.ChangeTracker.HasChanges(). However, I can't find a way to add some data and reset HasChanges() status.

Is this possible to using model and classes generated by EF without open connection to database?

Should I build my own model and use EF only for writing to the database?

marbel82
  • 925
  • 1
  • 18
  • 39

1 Answers1

1

You can add your entities to the context using the Attach method:

dbContext.MyTable.Attach(myRow);

This will add the entity with an EntityState of Unchanged:

dbContext.Entry(myRow).State == EntityState.Unchanged;

Once you apply changes to your entity, the entity tracker will detect these changes:

dbContext.ChangeTracker.HasChanges()

However, since your entities are not really coming from the database you may need to change the entity state to Added if you want to insert these records, and then dbContext.SaveChanges() will handle the rest.

if(dbContext.ChangeTracker.HasChanges())
{
    dbContext.Entry(myRow).State = EntityState.Added;
    dbContext.SaveChanges();
} 

For more info see this post.

HTH

Canica
  • 2,650
  • 3
  • 18
  • 34
  • "you may need to change the entity state to Added" that's exactly what I'm doing with dataset :). Thank you for your answer. Do you know how to programmatically set connection parameters and remove entity framework configuration from App.config? – marbel82 Aug 12 '19 at 08:13
  • 1
    @marbel82 Try this: https://stackoverflow.com/questions/34350851/entity-framework-6-set-connection-string-in-code – Canica Aug 12 '19 at 13:15