重复的ID生成

时间:2019-06-02 04:58:15

标签: asp.net-web-api azure-cosmosdb guid

我正在使用asp.net核心Web api和cosmos db创建一个项目。我将id生成为guid值,我会自动生成id。但是会创建重复值。

work.cs文件:

 public class work
    {
        [JsonProperty("id")]
        public Guid Id { get; set; }

        [JsonProperty("name")]
        public string name { get; set; }

        public List<Industy> Industy { get; set; }
        public work()
        {
            if (Id == null)
            {
                Id = Guid.NewGuid();
            }
            else
            {
                Id = Id;
            }

        }
    }

Industry.cs文件:

    {

        [JsonProperty("Id")]
        public Guid Id { get; set; }

        [JsonProperty("IdustryId")]
        public int IdustryId { get; set; }

        [JsonProperty("IdustryName")]
        public string IdustryName { get; set; }


        public Industy()
        {
            if (Id == null)
            {
                Id = Guid.NewGuid();
            }
            else
            {
                Id = Id;
            }
        }

    }

输出:

  {
    "id": "00000000-0000-0000-0000-000000000000",
    "Name": "string",
    "industy": {
      "id": "00000000-0000-0000-0000-000000000000",
      "IdustryId": 0,
    }
  }

如果我输入多个不带id的值,则显示错误,id已存在。请帮我修复它。

3 个答案:

答案 0 :(得分:0)

在两个模型中都将public Guid Id { get; set; }标记为可空:

public Guid? Id { get; set; }

Guid是一种结构和值类型。这意味着您必须与默认值(而不是null)进行比较或将其标记为可为空。

答案 1 :(得分:0)

您可以在属性上方定义属性

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
public Guid Id { get; set; }

也可以使用Fluent Api。在下面的OnModelCreating方法中的DbContext中编写代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Industy>().Property(x => x.ID).HasDefaultValueSql("NEWID()");
}

答案 2 :(得分:0)

@mexanich有很好的解决方案。您仍然可以尝试另一种方法。如果您不想将属性更改为nullable,请按如下所示更新条件。同样也不需要else块。您可以消除它。

if (Id == default(Guid))
{
    Id = Guid.NewGuid();
}