代码之家  ›  专栏  ›  技术社区  ›  Anton Putov

SaveChanges()调用实体框架后,无法看到数据库中的更改

  •  2
  • Anton Putov  · 技术社区  · 12 年前

    我有一张桌子 Device 只有一列 UID nvarchar(128) 这是我的实体:

    [Table( Name="Device" )]
    public class Device
    {
        [Key]
        public string UID { get; set; }
    }
    

    当我试图插入实体并提交对数据库的更改时,一切都可以。但在数据库中并没有添加新行。如果我试图用相同的UID重复此操作,我会被拒绝

    违反PRIMARY KEY约束“PK_dbo.Devices”。无法在对象“dbo.Devices”中插入重复的密钥。重复的密钥值为。。。

    发生了什么?

    编辑:

    以下是我的背景:

    public class DeviceContext :  BaseDbContext, IDbContext
    {
        public DbSet<Entity.Device> Device { get; set; }
    
        public new IDbSet<T> Set<T>() where T : class
        {
            return base.Set<T>();
        }
    
        public int SaveChanges()
        {
            return base.SaveChanges();
        }
    
        public void Dispose()
        {
            base.Dispose();
        }
    }
    

    失败 SaveChanges() 方法 BaseDbContext 只是“连接字符串层”。

    DeviceContext context = new DeviceContext();
    context.Device.Add(new Device() { UID = id });
    context.SaveChanges();
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Sergey Berezovskiy    12 年前

    错误表示数据已保存。所以我认为你看错了数据库。验证您的 DbContext .

    顺便说一句,你可以通过观看 context.Database.Connection.ConnectionString 属性。