Entity Framework 6 - Save Changes

asp.net-mvc entity-framework entity-framework-6 sql

Question

I am trying to perform an insert with EF 6.

I have verified I have a connection to the database, because I can do a read:

List<Driver> drivers = DataContext.Drivers.ToList();

With a sql profiler, I can see this do a select on the database, and it returns an item I manually inserted.

I am trying to perform an insert like this:

var driver = new Driver();
driver.DriverName = "Blah";
DataContext.Drivers.Add(driver);
DataContext.ChangeTracker.HasChanges(); //false
DataContext.SaveChanges();

except nothing is inserted, and the changetracker seems to show that it has not detected any changes. I also saw suggestions to use .Attach but this had the same results.

Any help on what I am doing wrong?

Cheers


(MyEntities.Context.cs)

 public partial class MyEntities : DbContext
    {
        public MyEntities()
            : base("name=MyEntities")
        {
        }

public partial class MyDataContext : MyEntities
    {

public class SqlDataService : DataServiceBase<...Data.MyDataContext>
    {

//where I am trying to do the insert with the code above

edit: No not using code first (not that i'm aware of!) not sure if the above code samples help, but show how I have set up my classes

1
4
4/23/2014 8:19:00 AM

Popular Answer

It seems you have AutomaticTrackChanges turned off somewhere in your code. Try adding this line before the addition:

var driver = new Driver();
driver.DriverName = "Blah";
//Turning Automatic changes tracking on:
DataContext.Configuration.AutoDetectChangesEnabled = true;
DataContext.Drivers.Add(driver);
DataContext.ChangeTracker.HasChanges(); //True
DataContext.SaveChanges();

Note: AutoDetectChangesEnabled is usually turned off for performance considerations

1
8/7/2014 10:17:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow