使用 DML 把 sObjects 保存到数据库
跟随 Trail Together 进行学习
进行这一步骤时,想要跟专家一起学习吗?观看此视频,它是 Trail Together 系列的一部分。
(这部分内容从 21:37 开始,如果您想要倒回去再次观看步骤的开头部分可以从这里开始。)
创建并调整 sObjects
创建 Recruiting Account sObject(招聘帐户 sObject)并把它保存到数据库。
- 在 Developer Console 中,请打开 Execute Anonymous(执行匿名)窗口。
- 把现有代码替换为这个代码:
//From the Account class, instantiate an object named acct Account acct = new Account(); //Set the name attribute of the acct object to Recruiting acct.name='Recruiting'; //Use DML to save the acct object to the database Database.insert(acct); System.debug('A new account named ' + acct.name + ' was added ');
- 确认 Open Log(打开日志)被选中,然后单击 Execute(执行)。执行日志打开。
- 选中 Debug Only(仅限调试)。
- 查看调试消息,然后关闭日志。
在 createContact 方法中,创建联系人 sObject,填写它的属性,把它添加到 conList,然后把列表保存到数据库中。
- 在 CreateContactFromCan 类中,把现有代码替换为这个代码:
public with sharing class CreateContactFromCan { //Declare a method that returns void and accepts a Candidate list named candsFromTrigger public static void createContact (List<Candidate__c> candsFromTrigger) { //Instantiate a Contact list named conList List<Contact> conList = new List<Contact>(); //Declare a list FOR loop that uses an iteration variable named currentCandidate //to loop through the candsFromTrigger list for(Candidate__c currentCandidate:candsFromTrigger) { //Create a Contact and add it to conList //Set the FirstName, LastName, and Email attributes to match the //corresponding attributes of the currentCandidate object (First_Name__c, //Last_Name__c, and Email__c) conList.add(new Contact( //Set the AccountId for the contact(we'll do this in the next unit) //AccountId = candAccts[0].Id, FirstName = currentCandidate.First_Name__c, LastName = currentCandidate.Last_Name__c, Email = currentCandidate.Email__c) ); } //Save conList to the database Database.insert(conList); } }
- 保存 CreateContactFromCan 类。