【问题标题】:Entity Framework 6 - Save Changes实体框架 6 - 保存更改
【发布时间】:2014-06-07 22:28:20
【问题描述】:

我正在尝试使用 EF 6 执行插入。

我已验证我已连接到数据库,因为我可以进行读取:

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

使用 sql profiler,我可以看到这对数据库进行了选择,并返回了我手动插入的项目。

我正在尝试执行这样的插入:

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

编辑:不首先使用代码(不是我知道的!)不确定上面的代码示例是否有帮助,但显示我是如何设置我的类的

【问题讨论】:

  • 你先用code吗?如果是这样,请提供您的上下文类
  • 您在MyDataContext 中还做什么?通常,将项目添加到DbSet 应该会导致更改跟踪器发生更改。看起来您所做的其他修改阻止了这种情况。

标签: sql asp.net-mvc entity-framework entity-framework-6


【解决方案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 通常是关闭的

【讨论】:

    猜你喜欢
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多