What is the difference between service.Create and orgContext.AddObject? - dynamics-crm

I find that there are two ways at least to create a record in an entity like the following.
Common Part
var record = new someEntity()
{
attribute1="test1",
attribute2="test2"
};
var service = new OrganizationService("CrmConnectionString");
Part A
service.Create(record);
Part B
var orgContext = new OrganizationServiceContext(service);
orgContext.AddObject(record);
orgContext.SaveChanges();
What is the difference?And which is better?

Part A uses the raw create method of the organization service proxy. This operation directly creates the record.
Part B makes use of the OrganizationServiceContext, which implements the Unit of Work pattern. Your operations are not transmitted to the server until you call SaveChanges()
Which is better? It depends on your requirements. If you only want to create a record on the go -> use the service. If you do multiple things which form a logical unit take version B.

Related

Eager loading for reference

I wonder if it is possible to load reference data in the first call. In my case I want to load the patient reference in the Encounter Resource. As I know I always need the patient data I want to avoid to to do an additional call to get the patient data.
The server is HAPI FHIR and the client firely .Net API
Yes, that is possible. Your request will have to be a search, that way you can include any referenced resources.
On REST level it looks like this:
GET <hapi_server>/Encounter?_include=patient
Add any filters you have. For example if you have a specific encounter you would add &_id=<technical_id>.
With the FhirClient from the .Net api, the code looks like this:
var c = new FhirClient("<hapi_server");
var q = new SearchParams().Include("Encounter:patient");
q.Add("_id", "<technical_id>");
var result = c.Search<Encounter>(q);

Deadlock on Linq to Entity Framework Core 2.0 Table

I'm getting what I think to be a deadlock when trying to run a bunch of linq queries in parallel.
I am running a Task.WhenAll() on this method:
public async Task<MetabuildScan> GetLatestMetabuildScanAsync(string buildId)
{
var metabuildScanStatuses = new[] { "Completed", "Referenced" };
// Get the latest metabuild scan for this image build
var latestScan = await (from scan in _qsaContext.MetabuildScans
where scan.SoftwareImageBuildId == buildId
&& metabuildScanStatuses.Contains(scan.SIScanStatus)
orderby scan.SIScanStartedOn descending
select scan).FirstOrDefaultAsync();
// If there is a related scan, then use that one, else, use the one we just got
var latestCompletedScanId = latestScan?.RelatedScanId ?? latestScan?.Id;
return await _qsaContext.MetabuildScans
.FirstOrDefaultAsync(scan => scan.Id == latestCompletedScanId);
}
I am getting a System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
_qsaContext was created using Entity-Framework Core.
At first, I thought the FirstOrDefaultAsync would fix my issue (I had a non-asynchronous FirstOrDefault in there at first), but it didn't.
I'm wondering what the best solution to get around this deadlock would be. The table I am selecting from is a large table, so I can't pull the whole table into memory.
As usual, wrap your query in try/catch and repeat your transaction.
Entity Framework DbContext is not thread safe. You can't run parallel queries against it like you are attempting to do.
If you need to have a shared context for your queries that you'll need to await each one individually and sequentially.
If they don't need a shared context but do need to run in parallel then you'll need to have a separate context for each query.
If using a DI framework, perhaps you can look into making your DbContext Transient (instead of what I'm assuming is Scoped) and injecting that into a query class that will call your query methods.

How to get Flux<T> from Mono<K> in Spring Reactive API?

I have two independent collections in NoSQL document db Photo and Property where Photo has propertyId parameter meaning that I can find all photos that belong to a given property like a house. Normally without reactive I would simply do:
Property property = ....
List<Photo> = photoService.findByPropertyId(property.getId());
Just two lines. How to do above in Reactive Programming when I have
`Mono<Property> and I want to find Flux<Photo>
without using block()?` Assume aphotoService.findByPropertyId return List and in reactive case it returns Flux.
You should use flatMapMany, which triggers an async processing from the Mono's value which can emit multiple elements:
Flux<Photo> photoFlux = propertyMono
.flatMapMany(prop -> photoService.findByPropertyId(prop.getId()));

Connecting to multiple cores at runtime

Is there a way to define a connection to a new Solr core on the fly, based on dynamic data?
We have a scenario where our Solr installation has multiple Cores/Indexes for the same type of document, separated by date (so a given week's documents will be on Index 1, the previous week's on Index 2, etc).
So when I receive my query, I check to see the required date range, and based on it, I want to query a specific core. I don't know in advance, at startup, which cores I will have, since new ones can be created dynamically during runtime.
Using the built-in ServiceLocation provider, there's no way to link two different Cores to the same document class. But even if I use a different DI container (currently Autofac in my case), I still need to specify all Core URLs in advance, during component registration.
Is there a way to bypass it except for always creating a new Autofac Container, generating the ISolrOperation<> class from it, and releasing it until the next time I need to connect to a core?
Mauricio Scheffer (developer of Solr.Net)'s comment confirmed that there's no built-in support for connecting to different index URLs on the fly. So instead of instantiating the internal objects myself, I used a hack on top of my existing Autofac based DI container:
public ISolrOperations<TDocument> ConnectToIndex<TDocument>(string indexUrl)
{
// Create a new AutoFac container environment.
ContainerBuilder builder = new ContainerBuilder();
// Autofac-for-Solr.Net config element.
var cores = new SolrServers
{
new SolrServerElement
{
Id = indexUrl,
DocumentType = typeof (TDocument).AssemblyQualifiedName,
Url = indexUrl,
}
};
// Create the Autofac container.
builder.RegisterModule(new SolrNetModule(cores));
var container = builder.Build();
// Resolve the SolrNet object for the URL.
return container.Resolve<ISolrOperations<TDocument>>();
}

Entity Framework--Filter Data At Load Time

I’m building an MVC3 application with form authentication and a single hierarchical entity. The entity has a Region object as the “root” with several other objects. It looks something like:
Region->Language->objectA->objectB
Region->Application->….
Each user (other than administrators) is associated with single region. I'd like to limit the data loaded to the entity based on the user’s region. I’m not too familiar with EF. Is this appropriate or is there a better approach? How would I implement the best approach
You can certainly filter the data returned via Entity Framework. The code would look something like this:
using (MyContext ctx = new MyContext())
{
var filtered = (from r in ctx.Regions where SOME_CONDITIONS select r);
// Do stuff with filtered (which is an IEnumerable<Region>)
}
Note that you may need to use Include to load related objects, e.g.
ctx.Regions.Include("Language").Include("Application")
see http://msdn.microsoft.com/en-us/library/bb896272.aspx

Resources