App Engine emulated datastore - strange observation - google-cloud-datastore

I was experimenting with 'datastore' on my machine. Using this code.
Key parentKey = KeyFactory.createKey("parent", "parentId");
try {
// Entity parent = new Entity("parent", "parentId");
// parent.setUnindexedProperty("property1", "value1");
// ds.put(parent);
Entity savedParent = ds.get(parentKey);
// savedParent.setUnindexedProperty("property1", "value3");
// ds.put(savedParent);
// Entity child = new Entity("child", "childId", savedParent.getKey());
Entity child = ds.get(KeyFactory.createKey(savedParent.getKey(), "child", "childId"));
child.setUnindexedProperty("property1", "val2");
ds.put(child);
// logger.info("Saved child.");
} catch (EntityNotFoundException e) {
throw new RuntimeException(e);
}
First I saved parent entity and set property on it to "value2" then I added a child entity with property val1. Then I updated parent property to value3. Then I updated property on child to val2.
Then I found out in the admin console, that value of the property on the parent is back to value2. I repeated it again with the same result. Am I missing something? Or is this some kind of bug?

I suppose, this is manifestation of eventual consistency, right? I run each step in a new JVM instance, thinking that values must have been stored at the time I switched it off:-. Contradicting common sense, but correct in terms of emulation of eventual consistency....

Related

Set PurchReqLine.BuyingLegalEntity default value to blank

I encountered a problem in the development, requesting a new purchase request line of a purchase with a legal person with a default value of empty
I tried a variety of methods, the default value can not be overriden.
The following is my code.
[ExtensionOf(formDataSourceStr(PurchReqTable, PurchReqLine))]
final class IWS_PurchReqTable_FDS_Extension
{
public void initValue()
{
next initValue();
//ttsbegin;
PurchReqLine purchReqLine = this.cursor();
purchReqLine.BuyingLegalEntity = 0;
purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
this.rereadReferenceDataSources(); //Refresh value
this.reread();
this.research(1);
FormReferenceGroupControl BuyingLegalEntity = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity));
FormStringControl BuyingLegalEntity_DataArea = this.formRun().design().controlName(formControlStr(PurchReqTable, PurchReqLine_BuyingLegalEntity_DataArea));
BuyingLegalEntity.value(0);
BuyingLegalEntity.resolveChanges();
BuyingLegalEntity.referenceDataSource().research(1);
BuyingLegalEntity.modified();
//BuyingLegalEntity_DataArea.text('');
//BuyingLegalEntity_DataArea.modified();
purchReqLine.BuyingLegalEntity = 0;
purchReqLine.modifiedField(fieldNum(PurchReqLine,BuyingLegalEntity));
//purchReqLine.update();
//purchReqLine.insert();
//this.rereadReferenceDataSources();
//this.refresh();
//this.reread();
//this.resetLine();
//ttscommit;
}
//End
}
It is not totally clear to me what you are trying to do.
Most values are "born" zero or blank and if that is not the case for this field, something else is setting the field, maybe after your code in initValue is called. The cross reference may be of good value here to find the code that references the field.
First of, you should definitely not reference the controls, also calling modifiedField and research from here is a total no-go.
For a start try this:
public void initValue()
{
next initValue();
purchReqLine.BuyingLegalEntity = 0;
}
It simply sets the field to zero. Do not worry about the field control, it will be rendered from the buffer value after the call to initValue.
If that does not solve your problem, something else is setting the field. You can set a breakpoint here, then follow to code until the field is set. Also add the value to the watch list, maybe do conditional debugging.
If another extension for this datasource exist it may override your behaviour as the execution order of extensions is arbitrary.

How does Entity Framework decide whether to reference an existing object or create a new one?

Just for my curiosity (and future knowledge), how does Entity Framework 5 decide when to create a new object vs. referencing an existing one? I might have just been doing something wrong, but it seems that every now and then if I do something along the lines of:
using (TestDB db = new TestDB())
{
var currParent = db.Parents.Where(p => p.Prop == passedProp).FirstOrDefault();
if(currParent == null) {
Parent newParent = new Parent();
newParent.Prop = passedProp;
currParent = newParent;
}
//maybe do something to currParent here
var currThing = db.Things.Where(t => t.Prop == passedPropTwo).FirstOrDefault();
currThing.Parent = currParent;
db.SaveChanges();
}
EF will create a new Parent in the database, basically a copy of the currParent, and then set the Parent_ID value of currThing to that copy. Then, if I do it again (as in, if there's already two of those parents), it won't make a new Parent and instead link to the first one. I don't really understand this behavior, but after playing around with it for a while something like:
using (TestDB db = new TestDB())
{
var currParent = db.Parents.Where(p => p.Prop == passedProp).FirstOrDefault();
if(currParent == null) {
Parent newParent = new Parent();
newParent.Prop = passedProp;
currParent = newParent;
}
//maybe do something to currParent here
var currThing = db.Things.Where(t => t.Prop == passedPropTwo).FirstOrDefault();
currThing.Parent = db.Parents.Where(p => p.ID == currParent.ID).First();
db.SaveChanges();
}
seemed to fix the problem. Is there any reason this might happen that I should be aware of, or was there just something weird about the way I was doing it at the time? Sorry I can't be more specific about what the exact code was, I encountered this a while ago and fixed it with the above code so I didn't see any reason to ask about it. More generally, how does EF decide whether to reference an existing item instead of creating a new one? Just based on whether the ID is set or not? Thanks!
If your specific instance of your DBContext provided that specific instance of that entity to you, then it will know what record(s) in the database it represents and any changes you make to it will be proper to that(those) record(s) in the database. If you instantiate a new entity yourself, then you need to tell the DBContext what exactly that record is if it's anything but a new record that should be inserted into your database.
In the special scenario where you have multiple DBContext instances and one instance provides you this entity but you want to use another instance to work with and save the entity, then you have to use ((IObjectContextAdapter)firstDbContext).ObjectContext.Detach() to orphan this entity and then use ((IObjectContextAdapter)secondDbContext).ObjectContext.Parents.Attach() to attach it (or ApplyChanges() if you're also editing it - this will call Attach for you).
In some other special scenarios (your object has been serialized and/or you have self-tracking entities), some additional steps may be required, depending on what exactly you are trying to do.
To summarize, if your specific instance of your DBContext is "aware" of your specific instance of an entity, then it will work with it as if it is directly tied to that specific row in the database.

How to update an entity without a round-trip? (EF 4)

I tried the following:
public void UpdatePlayer(int id)
{
Player player = new Player() {ID = id};
player.Password = "12";
Entities.Players.Attach(player);
Entities.SaveChanges();
}
No change at the db.
What am I missing?
I think it might be because you're setting the values before you attach the object - the data context will not know what fields have changed. Try:
public void UpdatePlayer(int id)
{
Player player = new Player() {ID = id};
Entities.Players.Attach(player);
player.Password = "12";
Entities.SaveChanges();
}
attach is used for entities that already exist in the database, but you have to attach first, and then edit it, as another poster pointed out.
you should use .Add instead of .Attach if you are creating new items.
FYI Entity Framework 4 - AddObject vs Attach
As already mentioned when you attach entity it is set to Unchanged state so you have to manually set the state to Modified. But be aware that setting the state for whole entity can cause update of all fields. So if your Player entity has more than Id and Password fields all other fields will probably be set to default values. For such case try to use:
Entities.Players.Attach(player);
var objectState = Entities.ObjectStateManager.GetObjectStateEntry(player);
objectState.SetModifiedProperty("Password");
Entities.SaveChanges();
You can also try setting password after attaching the entity:
Entities.Players.Attach(player);
player.Password = "12";
Entities.SaveChanges();
When you attach an entity using Attach method, the entity will go into Unchanged EntityState, that is, it has not changed since it was attached to the context. Therefore, EF will not generate necessary update statement to update the database.
All you need to do is to give a hint to EF by changing the EntityState to Modified:
Entities.Players.Attach(player);
Entities.ObjectStateManager.ChangeObjectState(player, EntityState.Modified)
Entities.SaveChanges();

Committing new data to database via EF, Errors ensue with Attaching/Adding

So I'm starting out with EF on my website (C#) and Ive run into a bit of a snag. A user can either create or modify data and they will do that with the selection screen (page 1). If a user selects to create new data, I will perform the following code:
Program newProg = new Program();
using (DatabaseEntities context = new DatabaseEntities())
{
Guid id = new Guid(list.SelectedValue);
var itemString = from item in context.Set where item.Id == id select item;
Item selectedItem = itemString.ToList()[0];
newProg.Items.Add(selectedItem);
context.AddToProgramSet(newProg);
context.Detach(newProg);
}
Pretty much creating a new instance of the 'Program' which will be passed along each user control until the user is ready to submit to the database. At that point the following code will be executed:
using (DatabaseEntities context = new DatabaseEntities())
{
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
context.SaveChanges();
}
Unfortunately when I get there, I receive the following message:
The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
at this line:
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
Also, when I add the following line prior to the previous:
context.Attach(this.SummaryControl.SelectedProgram);
I get this error:
An object with a null EntityKey value cannot be attached to an object context.
Any help would be greatly appreciated. Thanks.
The root cause of this error is that you are attempting to add an Entity as a new Entity that already has its primary key set.
At what point do you add the Entities to your SummaryControl? Your first code snippet shows you adding the Entity:
...
newProg.Items.Add(selectedItem);
context.AddToProgramSet(newProg);
context.Detach(newProg);
...
Then you appear to add it again:
using (DatabaseEntities context = new DatabaseEntities())
{
context.AddToProgramSet(this.SummaryControl.SelectedProgram);
context.SaveChanges();
}
If newProg and this.SummaryControl.SelectedProgram are the same Entity, you've attempted to add it twice. Remove the context.AddToProgramSet(newProg); from the first snippet, do you work on the Entity, then add it to the ProgramSet.
Dave is right that the root cause is that the entity already has a primary key.
One thing that you do not show in your code is how:
Program newProg = new Program();
Becomes:
this.SummaryControl.SelectedProgram
One way that you could fix it is by saving newProg to the database before you start adding Items to it.

Get Object using id in flex?

Acctually
I want to remove Child from VBox , i have id of child , but i don't to have real object that i want to remove using removeChild function of VBox
var elem:Type_of_E = this["constructed_id_of_E"];
If you have the id of the child to be removed, you have the real object. id attribute in mxml creates a public variable by it's value and store a reference to the object in that variable.
if(childId != null)
vbox.removeChild(childId);
else
trace("Normally this shouldn't happen in flex");
//or if you don't have VBox's id but you are sure that
//the child is in fact is parented by a container:
childId.parent.removeChild(childId);
Assuming you know the name of your VBOX before runtime:
yourVBOX.removeChild( yourVBOX.getChildByName('yourChildID') );
Read more on:
LiveDocs - Container - getChildByName
You might also want to set the "name" property on your component, such as :
myLabel.name = "LabelX";
myLabel.id = "LabelX"; // eventually
Then proceed to doing as the first answer said,
yourVBOX.removeChild( yourVBOX.getChildByName('LabelX') );
The thing to remember is to set the name as well as the ID, there is no such method as "getChildByID" :-)
getChildByID:
this.getChildren()[id]

Resources