如何插入新记录或保存对现有记录的更改

本文关键字:记录 保存 何插入 插入 新记录 | 更新日期: 2023-09-27 18:02:40

所以到目前为止,我已经能够为我的数据库编写查询函数,但是当涉及到编写更新函数时,我被难住了。我的查询功能工作得很好。

public PATIENT_IDS GetPatientIDS(string patientID)
{
    string ID = patientID;
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "''SQLExpress";
    builder.InitialCatalog = "pchr42563";
    builder.IntegratedSecurity = true;
    DataContext patientContext = new DataContext(builder.ConnectionString);
    PATIENT_IDS patient = (from p in patientContext.GetTable<PATIENT_IDS>() 
                           where p.PATIENT_ID == ID 
                           select p).First();
    return patient;
}

但是我不知道如何正确地附加到它以改变记录。我想应该是

public void UpdatePatientIDS(PATIENT_ID patient)
{
    PATIENT_ID newPatient = patient;
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "''SQLExpress";
    builder.InitialCatalog = "pchr42563";
    builder.IntegratedSecurity = true;
    DataContext patientContext = new DataContext(builder.ConnectionString);
    //this is the part that does not exist but I feel it should
    patientContext.PATIENT_ID.add(newPatient);
    patientContext.SubmitChanges();
}

我不知道这是否重要,但它是web服务代码的一部分,客户端应用程序正在通过代理传递PATIENT_ID。

这是我在合同中找到的PATIENT_IDS类的定义

namespace PCHRContracts
{
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Runtime.Serialization;
[Table(Name = "PATIENT_IDS")]
[DataContract]
public partial class PATIENT_IDS
{
    public PATIENT_IDS()
    {
        this.ALLERGIES = new HashSet<ALLERGy>();
        this.CONDITIONs = new HashSet<CONDITION>();
        this.IMMUNIZATIONS = new HashSet<IMMUNIZATION>();
        this.MED_PROCEDURE = new HashSet<MED_PROCEDURE>();
        this.MEDICATIONS = new HashSet<MEDICATION>();
        this.TEST_RESULTS = new HashSet<TEST_RESULTS>();
    }
    [Column]
    [DataMember]
    public string PATIENT_ID { get; set; }
   //other code
}

如何插入新记录或保存对现有记录的更改

您需要使用InsertOnSubmit():

DataContext patientContext = new DataContext(builder.ConnectionString);
//this is the part that does not exist but I feel it should
patientContext.PATIENT_IDS.InsertOnSubmit(newPatient);
patientContext.SubmitChanges();

好吧,在烦恼了几个小时后,我认为应该是如此简单,我弄明白了,虽然我不知道为什么它必须是这样的,所以没有其他的例子在网络上有这样的

patientContext.GetTable<PATIENT_IDS>().InsertOnSubmit(newPatient);

我的线索应该是我自己之前在我的GetPatient()函数中的代码

PATIENT_IDS patient = (from p in patientContext.GetTable<PATIENT_IDS>() 
                       where p.PATIENT_ID == ID 
                       select p).First();

谢谢大家的帮助!