如何插入新记录或将更改保存到现有记录

时间:2014-05-11 00:14:44

标签: c# sql datacontext

到目前为止,我已经能够为我的数据库编写一个查询函数,但在编写更新函数时我很难过。我的查询功能运行得很好。

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。

以下是我在conract中找到的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

}

2 个答案:

答案 0 :(得分:0)

您需要使用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();

答案 1 :(得分:0)

好吧,经过几个小时的思考,我认为应该如此简单,我想出来了,虽然我不知道为什么它必须像这样,所以网上没有其他例子就像这样。

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();

谢谢大家的帮助!

相关问题