Is it possibile to update an entity saved into my database with Graph? - core-data

i am using the Graph library in order to save my data correctly.
I was wondering, if there's a way to update an existing Entity, without duplicate the entity 2 times: user will be allowed to update just two values of the entity.
Also, i would like to know if there's a proper save method
I give you an example
let person = Entity(type: "Person")
person["name"] = //not editable
person["work"] = //editable
person["age"] = //editable
graph.sync() //or something like graph.update
Writing this, i am just creating a new entity, which is not what i want. Maybe, i have to search for the entity, delete that every time, and insert the new one?Hope not.
Thank you for any help you could give!

yes, you can update Entities.
You need to search for the one you want to update first. For example:
let graph = Graph()
let search = Search<Entity>(graph: graph).for(types: "Person")
for entity in search.sync() {
// do something
}
Once you have the entity you want to update, you can set any property, group, or tag as per usual.
entity["name"] = "Daniel"
From there you need to call graph.sync() or graph.async() so that all is saved.
Thats it :)

Related

How to change the value of a certain core data across VCs/ How to know the index of a created CoreData?

I start from a TableView to create and store user information. This is how I create a core data entity called "Trials" in CreateTrialViewController. And I can successfully fetch it in the tableViewController after I come back to it.
let trial : Trials = NSEntityDescription.insertNewObjectForEntityForName("Trials", inManagedObjectContext: self.managedObjectContext!) as? Trials
{
trial.project = theProject.text
trial.record = theRecord.text
trial.notes = theNotes.text
trial.percentile = ""
managedObjectContext?.save(nil)
}
'
But after I create the Trial, I will get some calculated results from the accelerometer in the next measureViewController, and I want to save the result into 'trial.percentile'.
I have already converted the results into a string, so I can write it directly into the core data attribute. But how can I know the index of this core data that I just created? Should I try to use 'segue' to transmit?
In the tableView it fetches in a ascending sequence of date, so the index is clear. But here in the following VC how to know the index? I still couldn't figure this out by myself... The sequence of my VCs is: TableViewController -> CreateTrialViewController -> MeasureViewController -> TableViewController (start again)
Your table view controller can keep a reference to the newly created object. Insert the object (trial) in the original view controller and pass it on to the next controller in prepareForSegue. So the CreateTrialViewController starts out with a blank object to which the table view controller has a reference.
You configure the object, go to the measure controller, modify the object. When done, you pop these two controllers from the navigation stack and are back in your original table view controller.
Because your table view controller has the NSFetchedResultsControllerDelegate enabled, it will update itself to reflect the data of your new object. Remember, you still have a reference to this object, so you can just use indexPathForObject to retrieve its index path.

Can't set Orchard field values unless item already created

I seem to be having a problem with assigning values to fields of a content item with a custom content part and the values not persisting.
I have to create the content item (OrchardServices.ContentManager.Create) first before calling the following code which modifies a field value:
var fields = contentItem.As<MyPart>().Fields;
var imageField = fields.FirstOrDefault(o => o.Name.Equals("Image"));
if (imageField != null)
{
((MediaLibraryPickerField)imageField).Ids = new int[] { imageId };
}
The above code works perfectly when against an item that already exists, but the imageId value is lost if this is done before creating it.
Please note, this is not exclusive to MediaLibraryPickerFields.
I noticed that other people have reported this aswell:
https://orchard.codeplex.com/workitem/18412
Is it simply the case that an item must be created prior to amending it's value field?
This would be a shame, as I'm assigning this fields as part of a large import process and would inhibit performance to create it and then modify the item only to update it again.
As the comments on this issue explain, you do need to call Create. I'm not sure I understand why you think that is an issue however.

Assigning a value to the primary field in code fails

I have a custom entity named eld_timereg. This entity has an attribute named eld_name (which is the primary field). Records are created in a generic handler (after pushing a button in the ribbon). I'm using late binding.
var myService = ...;
var t = new Entity( "eld_timereg" );
t["field1"] = "abc";
.
.
.
t["eld_name"] = GenerateAnUniqueStringCode("ZXC");
// returns something like ZXC-16398-T1VC
return myService.Create(t);
The record is created without any error. Checking the entity in SSMS, the value is blank although it is a required field.
What is happening here?
Found the problem. You put me on the right track James. Thank you for that. The eld_name attribute was overwritten in the plug-in (I forgot). Here it should be filled with some information. This was going wrong and always returned a null.

Access detail element of a collection inside a section in openxava

How can I access the details element of a collection entity which is inside one section of another entity with openxava? For example, in the view of entity A, we have section {S1,S2,S3} and inside section S3 view, we have {collection of entity B}. Now I want to access the detail element of entity B, so that i can fill the element in an action controller. How do I do that?
Get the collection directly from the view, in this way:
Collection myCollection = getView().getSubview("myCollection").getCollectionObjects();
It must work even with oldest OpenXava versions
Obtain the entity associated to the view and get the collection from it. Since OpenXava 4.3 you can do it in this way:
MyEntity myEntity = (MyEntity) getView().getEntity();
Collection myCollection = myEntity.getMyCollection();
If you're using an OX previous to 4.3 do it in this way:
Map keyValues = getView().getKeyValuesWithValue();
if (!keyValues.isEmpty()) {
MyEntity myEntity = (MyEntity)
MapFacade.findEntity(getView().getModelName(), keyValues);
Collection myCollection = myEntity.getMyCollection();
}
You can do it in several ways. Here you have one, I have used it with some references that I want to modify from inside of an action called by the base module (which should work with your collection):
Query q = XPersistence.getManager().createQuery("JPQL QUERY TO RETRIVE THE COLLECTION WITH :parameterIfNeeded");
q.setParameter("parameterIfNeeded", "value");
List entityBList = q.getResultList();
if (getView().getModelName().equalsIgnoreCase("yourBaseModelViewName")) {
getView().getSubview("yourSubViewName").setModel(entityBList);
getView().getSubview("yourSubViewName").refresh();
}
You must to be using OX 4.6 to be able to use setModel(). And remember that the "yourSubViewName" is the name of the property for your collection into the base model.
I have not tested that code with a collection, so make the adjustments according to your needs, maybe you will need to CAST the query result list or something.

Entity Framework 4.1 & existing database

Hi I have an existing database with a table with 30 fields, I want to split the table into many models so I could retrieve/save fields that I need and not every time retrieve/save the whole object from the db. using c#.
I think I should be using Code-First. Could someone provide an example or a tutorial link?
thanks,
You don't need to split table to be able to load a subset of field or persist subset of fields. Both operations are available with the whole table mapped to single entity as well.
For selection you simply have to use projection:
var data = from x in context.HugeEntities
select new { x.Id, x.Name };
You can use either anonymous type in projection or any non-mapped class.
For updates you can simply use:
var data = new HugeEntity { Id = existingId, Name = newName };
context.HugeEntities.Attach(data);
var dataEntry = context.Entry(data);
dataEntry.Property(d => d.Name).IsModified = true; // Only this property will be updated
context.SaveChanges();
Or:
var data = new HugeEntity { Id = existingId };
context.HugeEntities.Attach(data);
data.Name = newName;
context.SaveChanges(); // Now EF detected change of Name property and updated it
Mapping multiple entities to single table must follows very strict rules and it is possible only with table splitting were all entities must be related with one-to-one relation (and there are some problems with more than two entities per split table in code first) or with table-per-hierarchy inheritance. I don't think that you want to use any of them for this case.

Resources