使用LINQ to SQL進行更新


Answers

public bool UpdateCustomerIno(CustomerInfo toUpdate)
{
    bool successfullySaved = false;

    var db = new DataClasses1DataContext();
    try
    {
        var dbCstInfo = db.CustomerInfos
            .Where(w => w.CustomerID == toUpdate.CustomerID)
            .SingleOrDefault();

        if (dbCstInfo != null)
        {
            dbCstInfo.FirstName = toUpdate.FirstName;
            dbCstInfo.LastName = toUpdate.LastName;
            db.SubmitChanges();
            successfullySaved = true;
        }
    }
    catch {
        successfullySaved = false;
    }
    return successfullySaved;
}
Question

如何根據LINQ to SQL中的特定ID更新記錄?




 DataClassesDataContext dc = new DataClassesDataContext();

 FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);

 fd.FatherName=txtFatherName.Text;
        fd.FatherMobile=txtMobile.Text;
        fd.FatherOccupation=txtFatherOccu.Text;
        fd.MotherName=txtMotherName.Text;
        fd.MotherOccupation=txtMotherOccu.Text;
        fd.Phone=txtPhoneNo.Text;
        fd.Address=txtAddress.Text;
        fd.GuardianName=txtGardianName.Text;

        dc.SubmitChanges();



在沒有更詳細的信息:

using(var dbContext = new dbDataContext())
{
    var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
    if(data != null)
    {
        data.SomeField = newValue;
    }
    dbContext.SubmitChanges();
}



Links