我正在尝试使用EF 6执行插入。
我已经验证我与数据库有连接,因为我可以读取:
List<Driver> drivers = DataContext.Drivers.ToList();
使用sql profiler,我可以看到这对数据库执行select操作,并返回我手动插入的项目。
我正在尝试执行这样的插入:
var driver = new Driver();
driver.DriverName = "Blah";
DataContext.Drivers.Add(driver);
DataContext.ChangeTracker.HasChanges(); //false
DataContext.SaveChanges();
除了没有插入任何内容,并且changetracker似乎表明它没有检测到任何更改。我也看到了使用.Attach
的建议,但结果相同。
对我做错的任何帮助?
干杯
(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
编辑:不首先使用代码(不是我知道!)不确定上面的代码示例是否有帮助,但是显示我如何设置我的类
答案 0 :(得分:1)
您的代码中某处似乎已关闭AutomaticTrackChanges。 尝试在添加之前添加此行:
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();
注意: AutoDetectChangesEnabled
通常因性能问题而被关闭