【问题标题】:Can't insert record.the given error "Table "tbCustomer" does not have the identity property. Cannot perform SET operation"无法插入记录。给定错误“表“tbCustomer”没有身份属性。无法执行 SET 操作”
【发布时间】:2019-10-08 17:18:32
【问题描述】:

我在表上没有身份列。我不需要名为 CountryID 的列的身份。我将来自 CountryId 列的客户端请求的 CountryID 值作为主键传递。一旦我执行存储过程,我就会收到提到的错误,因为“表没有身份属性。无法执行 SET 操作”。如何插入记录而不出现此错误?

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CountryID { get; set; }

    public string CountryName { get; set; }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int LanguageId { get; set; }

   var result =  await tDBContext.Query<SpResponseMessage>().FromSql("exec sp_synchCountry " +
                 "@p0, @p1, @p2",
                  objCountry.CountryID,
                  objCountry.CountryName
                  objCountry.LanguageId).SingleOrDefaultAsync();

【问题讨论】:

  • 你有什么问题?
  • 如何插入记录?
  • 您在 CountryID 中有身份吗?你能传递该列的“代码行”吗当心,如果你有,身份使用类似于“IDENTITY(1, 2)”,意味着从 1 开始并增加 2
  • 没有。我没有身份列。
  • 创建表 [dbo].[tbCountry]( [CountryId] [int] NOT NULL, [CountryName] [nvarchar](200) NULL, [LanguageId] [int] NOT NULL 约束 [PK_tbCountry1]主键集群([CountryId] ASC,[LanguageId] ASC)WITH(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON)ON [PRIMARY])ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

标签: c# sql-server asp.net-core-webapi ef-core-2.2


【解决方案1】:

如果您想将多个属性配置为实体的键(称为复合键)。复合键只能使用 Fluent API 配置 - 约定永远不会设置复合键,您不能使用数据注释来配置一个。

 public class MyDbContext:DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options):base(options)
    { }

    public DbSet<Country> tbCountry { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Country>()
            .HasKey(c => new { c.CountryID, c.LanguageId });
    }
}

参考:https://docs.microsoft.com/en-us/ef/core/modeling/keys#fluent-api

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-03-11
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多