gpt4 book ai didi

c# - Dapper 插入到具有复合 PK 的表中

转载 作者:太空狗 更新时间:2023-10-29 18:22:12 24 4
gpt4 key购买 nike

我有一个表有一个由两列组成的主键,这两列都不是自动递增的,我的 Dapper 插入(Dapper Extensions 的一部分)在插入时失败,说两列中的第一列没有允许 null,即使我传入的值不为 null。

学生:

StudentId (PK, not null)   \_ (combined to form primary key)
StudentName (PK, not null) /
Active -- just another column

C#:

public class Student {
public int StudentId { get; set; }
public string StudentName { get; set; }
public bool Active { get; set; }
}

var newStudent = new Student { StudentId = 5, StudentName = "Joe", Active = true };
var insertSuccess = myConn.Insert<Student>(newStudent);

错误:

Cannot insert the value NULL into column 'StudentId', table 'dbo.Student'; column does not allow nulls. INSERT fails.

由于某些原因,Dapper 没有获得值为 5 的 StudentId。我是否必须对组合了 PK 的表或具有 PK 的表做一些特别的事情 不是自动递增?谢谢。

最佳答案

添加 AutoClassMapper 将更改所有类的行为。如果您只想处理这个类,您可以只为这个类创建一个 Map。

public class StudentClassMapper : ClassMapper<Student>
{
public StudentClassMapper()
{
Map(x => x.StudentId).Key(KeyType.Assigned);
Map(x => x.StudentName).Key(KeyType.Assigned);
AutoMap(); // <-- Maps the unmapped columns
}
}

关于c# - Dapper 插入到具有复合 PK 的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22462987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com