When we create an Opportunity Line Item we basically link PricebookEntry record and Opportunity Record by creating a junction names OpportunityLineItem.So every time if we want to update unitprice(salesprice) price for OLI we need to update pricebook entry record since unit price is of Pricebook entry field and Total price is of OLI field.
1.Create a PriceBook
pricebook2 pb=new pricebook2();
pd.name='MyPriceBook';
pb.isActive=true;
insert pb;
2.Create a Product
Product2 prod = new Product2();
prod.Name = 'MyProduct';
prod.ProductCode = 'MyProduct';
prod.isActive = true;
insert prod;
3.Add(Link) a product to Pricebook
PricebookEntry pbEntry = new PricebookEntry();
pbEntry.Pricebook2Id = pricebookId;
pbEntry.Product2Id = prod.Id;
pbEntry.UnitPrice = 100.00;
pbEntry.IsActive = true;
insert pbEntry;
4.Create(Add) Opportunity Line Item(Opportunity Product).This assumes already have an opportunity created
OpportunityLineItem oli = new OpportunityLineItem(
OpportunityId = opp.Id;
Quantity = 5;
PricebookEntryId = pbEntry.Id;
TotalPrice =123;
insert oli;
1.Create a PriceBook
pricebook2 pb=new pricebook2();
pd.name='MyPriceBook';
pb.isActive=true;
insert pb;
2.Create a Product
Product2 prod = new Product2();
prod.Name = 'MyProduct';
prod.ProductCode = 'MyProduct';
prod.isActive = true;
insert prod;
3.Add(Link) a product to Pricebook
PricebookEntry pbEntry = new PricebookEntry();
pbEntry.Pricebook2Id = pricebookId;
pbEntry.Product2Id = prod.Id;
pbEntry.UnitPrice = 100.00;
pbEntry.IsActive = true;
insert pbEntry;
4.Create(Add) Opportunity Line Item(Opportunity Product).This assumes already have an opportunity created
OpportunityLineItem oli = new OpportunityLineItem(
OpportunityId = opp.Id;
Quantity = 5;
PricebookEntryId = pbEntry.Id;
TotalPrice =123;
insert oli;