【发布时间】:2020-01-02 06:42:44
【问题描述】:
public class Person
{
public int PersonId { get; set; }
public string SurName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateOfDeath { get; set; }
public Gender gender { get; set; }
public Person Father { get; set; }
public Person Mother { get; set; }
}
我想通过查询将父亲和母亲添加到数据库中。
create table Persons(
PersonId int primary key identity,
SurName nvarchar(50) not null,
LastName nvarchar(50) not null,
DateOfBirth date not null,
DateOfDeath date null,
Gender tinyint not null,
Father ??nvarchar(50) null,
Mother ??varchar(50) null
);
我不知道用什么作为类型。并且在其他任何地方都找不到。
public void InsertPerson(Person person)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
using (SqlCommand sqlCommand =
new SqlCommand("insert into Persons values (@surName, @lastName, @dateOfBirth, @dateOfDeath, @gender, @father, @mother);", sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@surName", person.SurName);
sqlCommand.Parameters.AddWithValue("@lastName", person.LastName);
sqlCommand.Parameters.AddWithValue("@dateOfBirth", person.DateOfBirth);
sqlCommand.Parameters.AddWithValue("@dateOfDeath", person.DateOfDeath);
sqlCommand.Parameters.AddWithValue("@gender", person.gender);
sqlCommand.Parameters.AddWithValue("@father", person.Father);
sqlCommand.Parameters.AddWithValue("@mother", person.Mother);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
最终我想在数据库中添加值。如果到目前为止是正确的。我想它不是,我已经问过了。 我还在上学,没有老师就遇到困难。提前感谢您的帮助:)
【问题讨论】:
-
你需要一个外键,基本上母亲和父亲列将是其他
Persons的主键 -
运行此代码时是否返回任何错误?如果有,请在此处显示错误。为什么你需要使用这个
public Person Father { get; set; } public Person Mother { get; set; }而不是使用像public string Father这样的普通数据类型?
标签: c# database class sqlcommand