如何使用存储在 ObservableCollection 中的值向数据库添加新行?

所以我有两个 ObservableCollections:


ObservableCollection<Student> studentslist

ObservableCollection<Subject> subjectslist

我将它们传递给我已经建立了与 sql 数据库的整个通信的类。


studentslist 包含以下传递的值:


StudentsList.Add(new Student { IdStudent = newStudentId, Name = NameBox.Text, Surname = SurnameBox.Text, Index = IndexBox.Text })

主题列表包含我的列表框中选中的复选框的值(我仍然不确定这是否正确):


var selectedSubjects = SubjectList.Where(subjects => subjects.IsChecked == true);

var selectedSubjectsCollection = new ObservableCollection<Subject>(selectedSubjects);

这是我的主题类:


public class Subject

    {

        public int IdSubject{ get; set; }

        public string subject{ get; set; }

        public bool IsChecked { get; set; }



        public override string ToString()

        {

            return $"{subject}";

        }

    }

现在在我的课堂上,负责与 sql 数据库的连接,我创建了获取这两个集合的方法,并根据它们的值我想在数据库中创建新记录:


public void addRecord(ObservableCollection<Student> studentslist, ObservableCollection<Przedmiot> subjectslist)

        {

            OpenConection();

            //...

            CloseConnection();

        }

在数据库中我有学生表:


Student(IdStudent, FirstName, LastName, IndexNumber)

和主题表:


Subject(IdSubject, Name)

就我从数据库中读取数据而言,我不知道如何以正确的方式将这些值传递给数据库中的相应值。


ABOUTYOU
浏览 152回答 1
1回答

忽然笑

我喜欢使用存储过程来做这种事情,以最大限度地减少应用程序中的 T-SQL 代码量。一个例子是:public static void InsertSubject(Przedmiot subject){&nbsp; &nbsp; using (SqlConnection conn = new SqlConnection("Connection String"))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SqlCommand command = new SqlCommand("dbo.InsertSubject", conn) { CommandType = CommandType.StoredProcedure };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; command.Parameters.Add(new SqlParameter("@IdSubject", subject.IdSubject));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; command.Parameters.Add(new SqlParameter("@Name", subject.subject));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; conn.Open();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; command.ExecuteNonQuery();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception ex)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // handle exceptions&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后,您将拥有一个具有相同签名的存储过程来执行INSERT,即:CREATE PROCEDURE dbo.InsertSubject&nbsp; &nbsp; @IdSubject int&nbsp; &nbsp; , @Name varchar(50)AS...GO如果你想传递整个集合,你可以foreach在上面的例子中实现一个循环。我个人喜欢在每次插入时调用一次这些方法并将其作为int返回方法(例如),这样我就可以传递一些数据,例如插入行的 ID。
打开App,查看更多内容
随时随地看视频慕课网APP