breeze saving entity with multiple keys - breeze

On server, EF mapping defines 2 keys for entity
HasKey(t => new { t.EpisodeId, t.ConsumerAdviceId });
Trying to save new entity from client
this.domainContext.newAddedEntity(EpisodeConsumerAdvice.typeName, {consumerAdviceId: consumerAdviceId, episodeId: this.episode.id });
everything saves correctly to db but
this._entityManager.saveChanges()
throws error "Internal Error in key fixup - unable to locate entity"

Related

Breezejs .net core 3 saving new entities issue

using BreezeJs for .net core 3.1
Issue with fixupKeys when saving new entity
throws "Unable to locate the following fully qualified EntityType name: "
Examining this: the _entityGroupMap entries use another fully qualified format than the keymappings object
e.g.
HoseColor:#Urflex.Webshop.Model (_entityGroupMap) <<==>> Urflex.Webshop.Model.HoseColor (keymappings)
How to resolve this?
problem solved. Overlooked some configuration in startup.cs file of the web api project.
As the breeze documentation states:
var mvcBuilder = services.AddMvc();
services.AddControllers().AddNewtonsoftJson(opt =>
{
// Set Breeze defaults for entity serialization
var ss = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
if (ss.ContractResolver is DefaultContractResolver resolver)
{
resolver.NamingStrategy = null; // remove json camelCasing; names are converted on the client.
}
ss.Formatting = Newtonsoft.Json.Formatting.Indented; // format JSON for debugging
});
// Add Breeze exception filter to send errors back to the client
mvcBuilder.AddMvcOptions(o => { o.Filters.Add(new GlobalExceptionFilter()); });

Identity throws "Invalid object name 'dbo.AspNetUserClaims'" after removing that table

I have removed the "AspNetUserClaims" table from my DB because I am not saving any claims information.
After creating a user I am trying to fetch user info by its user name and it returns an error:
"Invalid object name 'dbo.AspNetUserClaims'.".
IdentityResult result = await manager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var userInfo = manager.FindByName(user.UserName);
foreach (var myRole in myRoles)
{
manager.AddToRole(userInfo.Id, myRole.Name);
}
await AddToPreviousPasswordsAsync(user, user.PasswordHash);
}
In the UserManager class of Identity 2, the Entity Framework-backed UserStore will ensure the claims are loaded for the requested user.
This accesses the AspNetUserClaims table, which will throw an exception when your database doesn't contain that table.
Simply don't remove tables that are required by a library, or rebuild the library without the claims part. And you don't want to do the latter, because then you won't receive any updates from the official channel anymore, and have to manually patch it. This is no way to handle a security-related library, or generally any library for that matter.

breeze: querying local cache when using client-side model

Consider the below code. It works fine when getting data from the server. I have a custom data adapter (staffManagemetnService) which creates client-side entities from the json returned by the server.
However, if I make a call to executeQueryLocally, it fails and raises the following exception: Cannot find an entityType for resourceName: 'GetInternalResourcesByCompetence'. Consider adding an 'EntityQuery.toType' call to your query or calling the MetadataStore.setEntityTypeForResourceName method to register an entityType for this resourceName
var query = breeze.EntityQuery.from('GetInternalResourcesByCompetence').withParameters(parameters);
var result = self.manager.executeQueryLocally(query.using(dataService.staffManagementService));
if (result) {
return $q.resolve(result);
} else {
return this.manager.executeQuery(query.using(dataService.staffManagementService))
.then(function (data) {
return data.results;
})
.catch(function (err) {
logError('Restrieving resources days off failed', err, true);
});
}
I'm not sure what this means. Should it not work out-of-the-box since I've specifically asked breeze to use the custom dataAdapter ?
It's important to different between resource names and entity type names. Resource names are usually part of an endpoint and in plural (eg orders). Type names are typically singular (eg order).
Locally breeze cannot do much with the resource name, since it won't call the endpoint. Instead you ask for a certain entity type name.
You can map an entityType to a resourcename using the setEntityTypeForResourceName function:
metadataStore.setEntityTypeForResourceName('Speakers', 'Person');
See chapter "Resources names are not EntityType names" and the following chapters here: http://www.getbreezenow.com/documentation/querying-locally

Custom DataService adapter saveChanges method to set entities to Unchanged

I've implemented a custom DataService adapter for BreezeJS - I wanted to use Breeze with a RESTful back end service (not OData or ASP.NET Web API).
So far - decent results after a learning curve.
I'm having an issue that when I call save changes - afterwards my entities on the client do not get marked as 'Unchanged'. They keep the same entityState.
I assume it has something to do with the success handler of the AJAX request to the backend service (looking at the source code to the WebAPI adapter):
success: function(data, textStatus, XHR) {
if (data.Error) {
// anticipatable errors on server - concurrency...
var err = createError(XHR);
err.message = data.Error;
deferred.reject(err);
} else {
// HACK: need to change the 'case' of properties in the saveResult
// but KeyMapping properties internally are still ucase. ugh...
var keyMappings = data.KeyMappings.map(function(km) {
var entityTypeName = MetadataStore.normalizeTypeName(km.EntityTypeName);
return { entityTypeName: entityTypeName, tempValue: km.TempValue, realValue: km.RealValue };
});
var saveResult = { entities: data.Entities, keyMappings: keyMappings, XHR: data.XHR };
deferred.resolve(saveResult);
}
},
It looks like the response includes an array of 'Entities'. What do these 'Entities' look like? It echoes what the client sent with an updated entityAspect.entityState value (server responses with 'Unchanged')?
Is that what should be passed into the deferred.resolve call?
I've got a working solution for this.
In a nutshell here's what is required for the object that is passed to the
deferred.resolve(saveResult);
Call in the success handler of the save change AJAX request.
Server response should include information about how to map from the client generated id to the server generated id (if the server generated one). This can be one keyMapping property returned in the response (like the Breeze API controller does) or what my service does is return a keyMapping property as a child property of a particular resource
The client code should create an array of objects that look like:
{ entityTypeName: "fully qualified entity type name",
tempValue: "client generated id",
realValue: "server generated id"
}
this array is the keyMappings property of the saveResult object
the entities property of the saveResult object is a flat list of all the entities that were modified from the server. Because of the design of my service API, it can return an entity, and child entities embedded in it, which I had to traverse and pull out into a flat list. Additionally these entity objects should be 'raw' and not include the entityAspect property or anything Breeze might interpret as a 'real' entity.
Also - something that can also be helpful is to look at the new sample from the Breeze folks - the MongoDB Breeze sample. They've implemented a custom dataServiceAdapter that hooks up their NodeJS/MongoDB backend. That provided some additional insight as well.
Good luck!

Creating any entity record with mvc 3

im trying to save a record on a sql server 2008 DB using entityframework and mvc3.
{
using(entities store = new entities())
{
login log = new login() {
Username=username,
Thumbprint=thumbprint
};
store.login.AddObject(log);
store.SaveChanges();//crashes on this line of code
}
}
The code crashes and teh error is I cant save null in the Username column. My DB table does not allow null and im assigning values to the log entity object(username). If you do not understand what im trying to say, please ask.

Resources