简体   繁体   中英

Dynamics CRM 2016 c# use id of not yet existing entity

for my project, I have to create multiple Quotes and add products to it.
For performance reasons (about 5000 quotes) I am using "ExecuteMultipleRequest()".

This is about what I've got:

var quote = new Quote
{
    QuoteNumber = "123",
    Name = "test123",
    PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, Pricelevel.Id),
    CustomerId = new EntityReference(Account.EntityLogicalName, Customer.Id),
};
_requests.Requests.Add(new CreateRequest { Target = quote });

var quoteDetail = new QuoteDetail
{
    QuoteId = new EntityReference(Quote.EntityLogicalName, quote.Id),
    ProductId = new EntityReference(Product.EntityLogicalName, product.Id),
    IsPriceOverridden = true,
    PricePerUnit = new Money(20),
    Quantity = Convert.ToDecimal(5),
};
_requests.Requests.Add(new CreateRequest { Target = quoteDetail });

My problem is the quote.Id. I know it is empty until the server processes the request and creates the quote.

Is there a way to tell the server it should use the quotes new id for the quotedetail?
Or is my only way to create the quote itself and then create all details?
What can I do to increase performance if I have to do it this way?

Instead of sending CreateRequests explicity, you could change your code to use the OrganizationServiceContext , which locally tracks changes to objects before submitting them to CRM.

When using the OrganizationServiceContext, you can use AddRelatedObject to both add an object and link it to another one:

Adds a related entity to the OrganizationServiceContext and creates the link that defines the relationship between the two entities in a single request.

Alternatively you could manually call AddObject and AddLink .

You final code would look similar to the following:

using (var context = new OrganizationServiceContext(_serviceProxy))
{
    var quote = new Quote
    {
        QuoteNumber = "123",
        Name = "test123",
        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, pricelevel.Id),
        CustomerId = new EntityReference(Account.EntityLogicalName, customer.Id),
    };
    context.AddObject(quote);

    var quoteDetail = new QuoteDetail
    {
        ProductId = new EntityReference(Product.EntityLogicalName, product.Id),
        IsPriceOverridden = true,
        PricePerUnit = new Money(20),
        Quantity = Convert.ToDecimal(5),
    };
    context.AddRelatedObject(quote, new Relationship("quote_details"), quoteDetail);

    context.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM