gpt4 book ai didi

C# INSERT 与 INSTEAD OF INSERT TRIGGER

转载 作者:行者123 更新时间:2023-11-30 21:49:49 28 4
gpt4 key购买 nike

我的数据库中有一个表 Teacher:

TABLE Teacher
(
ID CHAR (7) NOT NULL ,
name VARCHAR (50) NOT NULL ,
surname VARCHAR (50) NOT NULL ,
email VARCHAR (50) NOT NULL ,
phone CHAR (13) NOT NULL
)

在数据库中,我有一个 INSTEAD OF INSERT 触发器,它根据姓氏和数字创建 ID 和电子邮件。当我插入 SQL Server 时一切正常。我能做到

INSERT INTO Teacher(name, surname, phone) 
VALUES('John', 'Doe', '+111111111111')

我正在这个数据库上实现 ORM。

public static String SQL_INSERT = 
"INSERT INTO \"Teacher\" VALUES (@ID, @name, @surname, @email, @phone)";

public static int Insert(Teacher teacher, Database pDb = null)
{
Database db;
if (pDb == null)
{
db = new Database();
db.Connect();
}
else
{
db = (Database)pDb;
}

SqlCommand command = db.CreateCommand(SQL_INSERT);
PrepareCommand(command, teacher);
int ret = db.ExecuteNonQuery(command);

if (pDb == null)
{
db.Close();
}

return ret;
}

private static void PrepareCommand(SqlCommand command, Teacher teacher)
{
command.Parameters.AddWithValue("@ID", teacher.ID);
command.Parameters.AddWithValue("@name", teacher.Name);
command.Parameters.AddWithValue("@surname", teacher.Surname);
command.Parameters.AddWithValue("@email", teacher.Email);
command.Parameters.AddWithValue("@phone", teacher.Phone);
}

问题是当我尝试从 ORM 插入时。我必须这样做,因为它不允许我在没有所有强制属性的情况下插入。

Teacher newTeacher  = new Teacher ();

newTeacher.ID = "";
newTeacher.Name= "John";
newTeacher.Surname= "Doe";
newTeacher.Email = "";
newTeacher.Phone= "+111111111111";

TeacherTable.Insert(newTeacher, db);

有什么方法可以插入而不必将空字符串分配给 ID 和电子邮件? it inserts fine ,但代码对我来说看起来很糟糕。感谢您的帮助。

最佳答案

如果您使用默认约束定义表,则在插入时将值设置为默认值,而无需触发器...

CREATE TABLE Teacher
(
ID CHAR (7) NOT NULL, --don't know what is the content here... In most cases an ID column with INT IDENTITY is perefered
name VARCHAR (50) NOT NULL CONSTRAINT DF_Teacher_name DEFAULT(''),
surname VARCHAR (50) NOT NULL CONSTRAINT DF_Teacher_surname DEFAULT('') ,
email VARCHAR (50) NOT NULL CONSTRAINT DF_Teacher_email DEFAULT('') ,
phone CHAR (13) NOT NULL CONSTRAINT DF_Teacher_phone DEFAULT('')
);

顺便说一句:我不会强制电话号码适合 13 个字符...

关于C# INSERT 与 INSTEAD OF INSERT TRIGGER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744495/

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