function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
M SreekanthM Sreekanth 

When i am traying to inserting in bulk way through apex i am getting DML Exception like Below

Line: 11, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactCrTrigger: execution of BeforeInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id a072w00000QiZlGAAV; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Class.ContactCrHandler.contactRelationshipByContact: line 11, column 1 Trigger.ContactCrTrigger: line 4, column 1: []

Trigger Code:=
-------------------
trigger ContactCrTrigger on Contact (after insert) {
    if(trigger.isAfter &&trigger.isInsert){
    ContactCrHandler cr = new ContactCrHandler();
        cr.contactRelationshipByContact(Trigger.new);
    }
     if(trigger.isAfter &&trigger.isUpdate){
    ContactCrHandler cr = new ContactCrHandler();
        cr.contactRelationshipByContact(Trigger.new);
    }
}
TriggerHandler:-
--------------------
public class ContactCrHandler {
    public void contactRelationshipByContact(list<contact> conList){
        list<contact_Relationship__c> crList = new list<contact_Relationship__c>();
        for(contact c:conList){
            if(c.Contact_Relationship_Lookup__c==true){
            contact_Relationship__c cr = new contact_Relationship__c();
                cr.Name=c.LastName;
                cr.Contact__c=c.id;
                crList.add(cr);
            }
            insert crList;
        }
    }
}

Bulk Insertion Code:=
----------------------------
public class BulkDeleteContact {
    public static void m1(){
        list<contact> conList = new list<contact>();
        for(integer i=0;i<300;i++){
            contact c = new contact();
            c.LastName='TestContact'+i;
            c.Phone='9283724738';
            c.Contact_Relationship_Lookup__c=True;
            conList.add(c);
        }
        insert conList;
    }
    public static void deletecon(){
        list<contact> conList=[SELECT id FROM contact WHERE createdDate=today];
        delete conList;
    }
}

Please Help me
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Did you got error while running the BulkDeleteContact class?

Thanks,
 
M SreekanthM Sreekanth
Yes Sai above mentioned error