向数据库添加记录失败

时间:2021-02-06 15:39:53

I have a program, which uses a GET call to get some data, I then need to insert the result inside the DB. I'm getting an error when I call the program:

我有一个程序,它使用GET调用来获取一些数据,然后我需要在DB中插入结果。我打电话给程序时收到错误:

DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

DbUpdateConcurrencyException:数据库操作预计会影响1行,但实际上会影响0行。自加载实体以来,数据可能已被修改或删除。有关理解和处理乐观并发异常的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=527962。

My table DDL :

我的桌子DDL:

CREATE TABLE [CampaignCustomerMatch](
  id int NULL,
  VisitorExternalId [nvarchar] (40)  NULL ,
  Url [nvarchar](250)  NULL,
  ReffererUrl [nvarchar](250)  NULL,
  ActivityDate  [nvarchar](25)  NULL
)

A part of my code which fails in the last line:

我的代码的一部分在最后一行失败:

 var container = JsonConvert.DeserializeObject<MarkedCampaigns>(json);
 foreach (var item in container.items)
 {
      repository.addMatch(item);
 }
 await repository.saveChanges();

addMatch code:

addMatch代码:

public void addMatch(CampaignCustomerMatch ccm)
{
    _context.CampaignCustomerMatch.Add(ccm);
}

saveChanges :

保存更改 :

public async Task saveChanges()
{
    await _context.SaveChangesAsync();
}

And my CampaignCustomerMatch class:

还有我的CampaignCustomerMatch类:

 public class CampaignCustomerMatch
 {
     [Key]
     public int id { get; set; }
     public string VisitorExternalId;
     public string Url;
     public string ReffererUrl;
     public string ActivityDate;
 }

I don't understand the error. While debugging, the container seems fine, the data is looking good as well. What am I doing wrong?

我不明白这个错误。在调试时,容器似乎很好,数据看起来也很好。我究竟做错了什么?

2 个解决方案

#1


0  

In general, EF Core is used migrations to create table which is called Code-First. It seems you created Table and Model separately.

通常,EF Core使用迁移来创建称为Code-First的表。您似乎分别创建了表和模型。

If you want to manually set id for CampaignCustomerMatch, follow steps below:

如果要手动为CampaignCustomerMatch设置ID,请执行以下步骤:

  1. Change CampaignCustomerMatch with { get; set; } for properties, otherwise, all of them will be null when inserting new records.

    使用{get;更改CampaignCustomerMatch组;对于属性,否则,插入新记录时所有属性都将为null。

    public class CampaignCustomerMatch
    {
        [Key]
        //[DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int id { get; set; }
        public string VisitorExternalId { get; set; }
        public string Url { get; set; }
        public string ReffererUrl { get; set; }
        public string ActivityDate { get; set; }
    }
    
  2. Explicit set id like below:

    显式设置ID如下:

        _ctx.CampaignCustomerMatch.Add(new CampaignCustomerMatch { id = 1000, Url = "www.google.com" });            
        await _ctx.SaveChangesAsync();
    

If you want id auto-generated, follow steps below:

如果您想要自动生成ID,请按照以下步骤操作:

  1. Change Table

    改变表

     CREATE TABLE [dbo].[CampaignCustomerMatch] (
    [id]                INT            IDENTITY (1, 1) NOT NULL,
    [VisitorExternalId] NVARCHAR (MAX) NULL,
    [Url]               NVARCHAR (MAX) NULL,
    [ReffererUrl]       NVARCHAR (MAX) NULL,
    [ActivityDate]      NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_CampaignCustomerMatch] PRIMARY KEY CLUSTERED ([id] ASC)
    );
    
  2. Change Model

    改变模型

      public class CampaignCustomerMatch
      {
         [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        public string VisitorExternalId { get; set; }
        public string Url { get; set; }
        public string ReffererUrl { get; set; }
        public string ActivityDate { get; set; }
    }
    

3.Insert Record without id

3.没有id的插入记录

_ctx.CampaignCustomerMatch.Add(new CampaignCustomerMatch { Url = "www.google.com" });
await _ctx.SaveChangesAsync();

#2


0  

There is an entire post about it in GitHub:

在GitHub中有一篇关于它的文章:

remove .ValueGeneratedNever(); from the model for ID (it is actually AutoIncrement INT primary key).

remove .ValueGeneratedNever();来自ID的模型(它实际上是AutoIncrement INT主键)。

#1


0  

In general, EF Core is used migrations to create table which is called Code-First. It seems you created Table and Model separately.

通常,EF Core使用迁移来创建称为Code-First的表。您似乎分别创建了表和模型。

If you want to manually set id for CampaignCustomerMatch, follow steps below:

如果要手动为CampaignCustomerMatch设置ID,请执行以下步骤:

  1. Change CampaignCustomerMatch with { get; set; } for properties, otherwise, all of them will be null when inserting new records.

    使用{get;更改CampaignCustomerMatch组;对于属性,否则,插入新记录时所有属性都将为null。

    public class CampaignCustomerMatch
    {
        [Key]
        //[DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int id { get; set; }
        public string VisitorExternalId { get; set; }
        public string Url { get; set; }
        public string ReffererUrl { get; set; }
        public string ActivityDate { get; set; }
    }
    
  2. Explicit set id like below:

    显式设置ID如下:

        _ctx.CampaignCustomerMatch.Add(new CampaignCustomerMatch { id = 1000, Url = "www.google.com" });            
        await _ctx.SaveChangesAsync();
    

If you want id auto-generated, follow steps below:

如果您想要自动生成ID,请按照以下步骤操作:

  1. Change Table

    改变表

     CREATE TABLE [dbo].[CampaignCustomerMatch] (
    [id]                INT            IDENTITY (1, 1) NOT NULL,
    [VisitorExternalId] NVARCHAR (MAX) NULL,
    [Url]               NVARCHAR (MAX) NULL,
    [ReffererUrl]       NVARCHAR (MAX) NULL,
    [ActivityDate]      NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_CampaignCustomerMatch] PRIMARY KEY CLUSTERED ([id] ASC)
    );
    
  2. Change Model

    改变模型

      public class CampaignCustomerMatch
      {
         [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        public string VisitorExternalId { get; set; }
        public string Url { get; set; }
        public string ReffererUrl { get; set; }
        public string ActivityDate { get; set; }
    }
    

3.Insert Record without id

3.没有id的插入记录

_ctx.CampaignCustomerMatch.Add(new CampaignCustomerMatch { Url = "www.google.com" });
await _ctx.SaveChangesAsync();

#2


0  

There is an entire post about it in GitHub:

在GitHub中有一篇关于它的文章:

remove .ValueGeneratedNever(); from the model for ID (it is actually AutoIncrement INT primary key).

remove .ValueGeneratedNever();来自ID的模型(它实际上是AutoIncrement INT主键)。