Entity being tracked despite AsNoTracking - linq

I have an object, Client, with a navigation property that is a list of Order objects. Whenever I retrieve a Client object, I include the list of Orders, with AsNoTracking().
public new IQueryable<Client> FindByConditionNoTracking(Expression<Func<Client, bool>> expression)
{
return this.ClientContext.Set<Client>().Include(s => s.Orders)
.Where(expression).AsNoTracking();
}
In my UpdateClient repository method, I take in a Client object. I then attempt to retrieve that original client from the database (using Include to get the child Orders), map the Client param to the original, and save to the database. Over here, I do not use AsNoTracking, because I specifically want the changes to be tracked.
public new void Update(Client client)
{
var id = client.ClientId;
var original = this.ClientContext.Clients.Include(s => s.Orders).Where(s => s.ClientId == id)
.FirstOrDefault<Client>();
original = _mapper.Map(client, original);
this.ClientContext.Update(original);
}
The error I am getting is that an instance of Order with the same key value is already being tracked. A few problems with that:
Wherever the Client and the child Orders are retrieved for the purposes of display I use AsNoTracking.
The only place where I retrieve without AsNoTracking is where I get the original within this very method.
The bug isn't with the parent property. If I was improperly retrieving the Client elsewhere, wouldn't I have this error with the Client id itself? But the error seems to be only with the navigation property.
All insight is appreciated!

If anyone else runs into this: Automapper, when mapping collections, apparently recreates the entire collection. I solved the above issue by using Automapper.Collections in my mapping configuration. Thanks to Mat J for the tip!

Related

extending datamodel in Microstream

I would like to extend an existing datamodel in Microstream with a new data object. E.g. I have Customers, with data records in Microstream, and I would like to add Vendors, with their own datastructure and data. As the database is not empty, I cannot start as if their is no data, however adding a list of Vendor to the dataroot doesn't seem to work. Microstream says the list is null when starting, which is correct, but I cannot add my new object to a null list. Can someone explain me how to add a vendor to my 'database' ?
You just need to add this List and store this object with the existing list again.
I received an answer from fh-ms # Microstream:
Hi, you are right, the vendors list is not present in the storage, so the field will be initialized with its default value (null).
There are several possibilities to introduce initial values to new fields.
One rather complex way would be to implement a Legacy Type Handler.
A far more simple one is just lazy initialization in your Customer type:
public List<Vendor> getVendors()
{
if(this.vendors == null)
{
this.vendors = new ArrayList<>()
}
return this.vendors;
}
And that works !

Parse-Server prevent fields from being added automatically

Right now, if I add a field to a Parse object and then save it, the new column shows up in the Parse dashboard.
For example, after running:
let media = new Parse.Object("Media");
media.set("foo", "bar");
await media.save();
I will have a new column called foo.
Is it possible to prevent this from happening?
Yes. This can be done using class-level permissions, which allow you to prevent fields being added to classes.
Parse lets you specify what operations are allowed per class. This lets you restrict the ways in which clients can access or modify your classes.
...
Add fields: Parse classes have schemas that are inferred when objects are created. While you’re developing your app, this is great, because you can add a new field to your object without having to make any changes on the backend. But once you ship your app, it’s very rare to need to add new fields to your classes automatically. You should pretty much always turn off this permission for all of your classes when you submit your app to the public.
You would have to add a beforeSave trigger for every one of your classes, keep a schema of all your keys, iterate over the request.object's keys, and see if there are any that do not belong in your schema. You can then either un-set them and call response.success(), or you can call response.error() to block the save entirely, preferably with a message indicating the offending field(s).
const approvedFields = ["field1", "field2", "field3"];
Parse.Cloud.beforeSave("MyClass", function(request, response) {
let object = request.object;
for( var key in object.dirtyKeys() ) {
if( approviedFields.indexOf(key) == -1 ) return response.error(`Error: Attempt to save invalid field: ${key});
}
response.success();
});
Edit:
Since this got a little attention, I thought I'd add that you can get the current schema of your class. From the docs: https://docs.parseplatform.org/js/guide/#schema
// create an instance to manage your class
const mySchema = new Parse.Schema('MyClass');
// gets the current schema data
mySchema.get();
It's not clear if that's async or not (you'll have to test yourself, feel free to comment update the answer once you know!)
However, once you have the schema, it has a fields property, which is an object. Check the link for what those look like.
You could validate an object by iterating over it's keys, and seeing if the schema.fields has that property:
Parse.Cloud.beforeSave('MyClass', (request, response) => {
let object = request.object;
for( var key in object.dirtyKeys() ) {
if( !schema.fields.hasOwnProperty(key) ) < Unset or return error >
}
response.success();
}
And an obligatory note for anyone just starting with Parse-Server on the latest version ,the request scheme has changed to no longer use a response object. You just return the result. So, keep that in mind.

WebApi OData formatter doesn't work for child elements

Following code converts the ViewModel query to model and then converts the returned result back to ViewModel as PageResult. All this works fine but when I try to use include as part of my default query(or even with the latest version as part of querycontext) then OData formatter plays funny and doesn't include child elements. I have debugged and confirmed that it actually contains child elements. This only happens for controllers that I extended from ODataController(so basically for the ones that are extended from ApiController all works fine but i need results in OData format).
Please note that I have also tried with the latest nightly build(Microsoft.Data.OData 5.5.0.0) and still it doesn't work for me.
Any help would highly be appreciated.
public class ProductsController : ODataController
{
APPContext context = new APPContext();
public PageResult<ProductViewModel> Get(ODataQueryOptions QueryOptions)
{
EdmModel model = new EdmModel();
ODataQueryContext queryContext = new ODataQueryContext(model.GetEdmModel(), typeof(Product));
var mappedQuery = new ODataQueryOptions(queryContext, QueryOptions.Request);
var results = new List<ProductViewModel>();
foreach (var result in mappedQuery.ApplyTo(this.context.Serials.Include("Status").Include("Category")))
{
AutoMapper.Mapper.CreateMap(result.GetType(), typeof(ProductViewModel));
results.Add(AutoMapper.Mapper.Map<ProductViewModel>(result));
}
PageResult<ProductViewModel> pr = new PageResult<ProductViewModel>(results.AsEnumerable<ProductViewModel>(), mappedQuery.Request.GetNextPageLink(), mappedQuery.Request.GetInlineCount());
return pr;
}
}
In OData related entities are represented as navigation links. So, if you have a customers feed, the related orders for each customer will not be part of the customers feed. Instead, they would be represented as navigation links. You can explicitly tell the OData service to expand the related entities using the $expand query option. So, if you want the related orders for each customer to be expanded, you should ask for the url ~/Customers?$expand=Orders.

How to use a Database Generated Identity Key in Web Api OData

I've managed to create number of readonly Web Api OData services following the tutorials here: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api. I'm therefore employing the ODataConventionModel builder to create the model from a set of entities (incidentally coming from a Telerik ORM). This all seems to work fine and I can happily issue queries, view the metadata and so forth on the service.
I've now tried to turn my attention to the other CRUD operations - firstly Create and have stumbled into a problem! Namely, the Post method fires correctly (CreateEntity) but the entity parameter is null - by doing a check against the ModelState.IsValid, it shows that the problem is a null ID (key) value. This is unsurprising because the database uses a Database Generated Identity for the ID column and therefore the ID would be created when the entity is saved into the database context.
I've therefore tried all sorts of ways of marking the ID column as database generated, but haven't managed to find anything. Strangely, I can't seem to find even one post of someone asking for this - surely I can't be the only one?!
I noted that when looking at the EF modelbuilder (for example here: http://forums.asp.net/t/1848984.aspx/1) there appears to be a means of affecting the model builder with a .HasDatabaseGeneratedOption property, but no similar option exists in the System.Web.Http.OData equivalent.
So the questions therefore are:
Is there a means of altering the model builder (or something else) so that the controller will accept the object and deserialize the entity even with a null key value?
If so, how can I do this?
If not, any suggestions as to other options?
I realise that I could potentially just populate the object with an (in this case) integer value from the client request, but this seems a) semantically wrong and b) won't necessarilly always be possible as a result of the client toolkit that might be used.
All help gratefully received!
Many thanks,
J.
You need to create a viewmodel for insert which does not contain the ID parameter. Use Automapper to map the properties of the incoming insert-model to your data entities.
The problem that you're having is that ID is a required attribute in your data model because it is your PK, except during insert, where it shouldn't be specified.
In my case, my database-generated key is a Guid.
As a work-around, in my TypeScript client code, I submit (via http POST) the object with an empty Guid like this: Note: ErrorId is the key column.
let elmahEntry: ELMAH_Error = {
Application: 'PTUnconvCost',
Host: this.serviceConfig.url,
Message: message,
User: that.userService.currentUserEmail,
AllXml: `<info><![CDATA[\r\n\r\n${JSON.stringify(info || {})}\r\n\r\n]]></info>`,
Sequence: 1,
Source: source,
StatusCode: 0,
TimeUtc: new Date(Date.now()),
Type: '',
ErrorId: '00000000-0000-0000-0000-000000000000'
};
Then, in my WebApi OData controller, I check to see if the key is the empty guid, and if so, I replace it with a new Guid, like this:
// POST: odata/ELMAH_Error
public IHttpActionResult Post(ELMAH_Error eLMAH_Error)
{
if (eLMAH_Error.ErrorId == Guid.Empty)
{
eLMAH_Error.ErrorId = Guid.NewGuid();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.ELMAH_Error.Add(eLMAH_Error);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (ELMAH_ErrorExists(eLMAH_Error.ErrorId))
{
return Conflict();
}
else
{
throw;
}
}
return Created(eLMAH_Error);
}

Entity Framework saves duplicates of one side in a one to many

I am having a problem with Entity Framework in my MVC 3 application. I have a users table, which is only ever populated with a new user row when a machine entity is created by a user that hasn't created any machines before, i.e. it only creates users it hasn't seen before. Each user belongs to a sector (division of the company) which also must be set before the user and the machine are saved. I have a default sector that new users are assigned to (so that this may be changed later on).
I have some code in my machine controller class for the creation of new machines that looks like this:
[HttpPost]
public ActionResult Create(Machine machine)
{
if (ModelState.IsValid)
{
// work out if the user exists in the database already
var users = userRepository.All.Where(u => u.Username == machine.User.Username);
if (users.Count() == 0)
{
// if the user entry doesn't exist we have to create it assigning a default sector
Sector defaultSector = null;
var defaultSectors = sectorRepository.All.Where(s => s.IsDefaultForNewUsers);
if (defaultSectors.Count() == 0)
{
// jebus! no default sector, so create one
defaultSector = new Sector() { Name = "Default", IsDefaultForNewUsers = true };
sectorRepository.InsertOrUpdate(defaultSector);
sectorRepository.Save();
}
else
{
defaultSector = defaultSectors.First();
}
machine.User.Sector = defaultSector;
}
else
{
machine.User = users.First();
}
machineRepository.InsertOrUpdate(machine);
machineRepository.Save();
return RedirectToAction("Index");
}
else
{
ViewBag.PossibleInstalledOS = installedosRepository.All;
ViewBag.PossibleLicenceTypes = licencetypeRepository.All;
ViewBag.PossibleUsers = userRepository.All;
return View();
}
}
[Edit] Here is the body of the InsertOrUpdate method from my Machine repository:
public void InsertOrUpdate(Machine machine)
{
if (machine.MachineId == default(int)) {
// New entity
context.Machines.Add(machine);
} else {
// Existing entity
context.Entry(machine).State = EntityState.Modified;
}
}
The problem I'm having with this code is that when I save the machine, it keeps creating a new user even though that user is already in the system. The line that finds the user works and retrieves the user as I would expect but entity framework doesn't seem to understand that I wish to use this user that I've found and not create a new one. So at the moment I have multiple identical users (except ID of course) in my users table. I want a one to many here so that multiple machines are owned by the same user.
Does anyone have any idea how I force entity framework to respect that there is already a user there that I want to tie the new machine to?
You didn't post the code for your InsertOrUpdate method but I suspect that that is where the problem is. I bet in that method at some point you do something equivalent to:
context.Machines.Add(machine);
When you call DbSet.Add (or change the state of an entity to Added) you are actually adding the whole graph to the context. This process will stop when it encounters an object that is being tracked by the context. So if you have a machine object that references a user object and neither of these objects are being tracked by the context, then both the machine object and the user object will be added to the context and end up in an Added state. EF will then insert them both as new rows in the database.
What you need to do, which was alluded to in the other answer, is make sure than EF knows that an existing user object does exist in the database by making sure it's state is Unchanged (or possibly Modified) and not Added when you save.
There are various ways that you could accomplish this and it's hard to know which is best for you without seeing more of how your app and repository work. One way is to make sure that the context used to query for the user is the same context as is used to save. This way EF will already be tracking the existing user object and will know not to add it when you call Add.
Another way is to let your repository know somehow whether or not the user object is new. Often people use the primary key to determine this--a zero key indicates a new object, non-zero indicates an existing object. You could also pass a flag into your repository.
You can then call Add to add the graph, but then set the state of the User object to Unchanged (or Modified if it might have been changed since it was queried) if it is an existing user. This will prevent EF from inserting a new user into the database.
Can you double check that your repositories are using the same data context? If not, you are essentially adding a new User entity to the machineRepository. Alternatively you could attach the user to the context for the machine repository, but you'll likely keep running into bugs like this.

Resources