CoreData with Relationships - how to avoid duplicate updates - core-data

I have CoreData with simple relationships as you can see below. One entity Word with 4 attributes and a Chapter entity with a one to many relationship (each word figures in only one chapter and chapters contains several words). When I try to import a file with a list of words and associated chapter, the chapters which are not yet in the database are created (which is what I want) but the chapters that already exists are created a 2nd time (new same entry in coredata). Is there an option I can activate in xcdatamodel to check and avoid duplicate entries on the relation entity?
Code details ->
fileprivate func saveAllWords(_ items: [(name: String, definition: String, example: String, chapter: String)]?) {
for item in items! {
let newWord = Word(context: self.context)
newWord.name = item.name.trimmingCharacters(in: .whitespaces)
newWord.definition = item.definition.trimmingCharacters(in: .whitespaces)
newWord.example = item.example.trimmingCharacters(in: .whitespaces)
newWord.option = 10 // option tag indicating that it's a new entry from external fileI generate a classic word
//
let myNewChapter = Chapter(context: self.context)
myNewChapter.name = item.chapter
newWord.chapter = myNewChapter
}
……
// Save the data in Core Data
do {
try self.context.save()
}
catch {
}
Any recommendation how to implement this uniqueness constraint to solve my duplicate issue?

You have to create a constraint for the unique attribute. It looks like you want the name of the Chapter to be unique
In your xcdatamodeld select your attribute, then right constraint and add they attribute.
Last but not least you will have to add merge policy for your Context, mostly likely in your AppDelegate. There are different merge policy. You should check them out which fits your needs most
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

Related

How to get source list types of particular list/record field?

Here is I have two entity custom fields with list/record type,
custom_dev_j15 entity field has a custom source list (eg: one, two, three, four, etc)
custom_qa_v93 entity field has a standard source list as an object (eg: customer )
I've two vendor entity custom fields as stated in screenshots of question,
custentity473 --> customer is selected as list source
custentity474 --> custom_dev_j15_m_list as selected as list source ( which is custom list)
Here is snippet that i used to get the options of these fields,
// Snippet
var fieldDetails = {};
var record = nlapiCreateRecord("Vendor");
var field = record.getField("custentity473");
var selectoptions = field.getSelectOptions();
for ( var i in selectOptions) {
var Option = {
id : selectOptions[i].getId(),
label : selectOptions[i].getText()
}
Options.push(Option);
}
fieldDetail["options"] = Options;
But my need is to get source list information like name of the list source (customer or custom_dev_j15_m_list) via suitescript
any idea on how to get this information?
Thanks in advance
I'm not sure I understand this question for what you're trying to do.
In NetSuite almost always, you accommodate to the source list types because you know that's the type, and if you need something else (e.g. a selection which is a combination/or custom selection you'll use a scripted field)
Perhaps you can expand on your use case, and then we can help you further?

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

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 :)

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.

Saving to a Entity that has Many To Many relationship

I have a set of tables (ConditionTemplate and KeyWord) that have a many to many relationship. In code I am trying to add a Keyword to a specific ConditionTemplate record. Unfortunately, when I think I'm adding a Keyword to a specific condition I'm getting an error as if it's adding a new Keyword without being associated to a condition.
An Image of my Model:
My Code:
Global Variables Creation:
EnterpriseEntities EE;
ConditionTemplate myConditionTemplate;
Load Global Variables:
EE = new EnterpriseEntities();
EE.Database.Connection.ConnectionString = Myapp.EnterpriseEntityConnectionString;
myConditionTemplate = EE.ConditionTemplates.Where(c => c.TemplateCode == "17D").FirstOrDefault();
The above code loads a single Condition with Many Keywords.
Available Keywords are in a listbox and the user pushed a button to select a keyword(s) to move to the condition. This is the code that handles that.
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = new KeyWord
{
KeyWordID = SelectedKeyWord.KeyWordID,
ID = SelectedKeyWord.ID,
Word = SelectedKeyWord.Word
};
myConditionTemplate.KeyWords.Add(NewKeyWord);
}
Then the user pushes a button to save changes and I call
EE.SaveChanges
Then I get this error:
System.Data.UpdateException: An error occurred while updating the
entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint
'IX_KeyWord'. Cannot insert duplicate key in object 'dbo.KeyWord'. The
duplicate key value is (ADJUDICATION). The statement has been
terminated.
If I remove the code that sets the word property (Word = SelectedKeyWord.Word
) when I create the keyword object I get this error.
System.Data.Entity.Validation.DbEntityValidationException: Validation
failed for one or more entities. See 'EntityValidationErrors' property for more details.
Which tells me the word field is required.
In order to tell EF that the KeyWords you selected already exist in the database and to avoid the problem you must attach them to the context:
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = new KeyWord
{
// You actually only need to set the primary key property here
ID = SelectedKeyWord.ID
};
EE.KeyWords.Attach(NewKeyWord);
myConditionTemplate.KeyWords.Add(NewKeyWord);
}
Edit
If the KeyWord entities are already attached to your context (because they have been loaded before with the same context for example) you can use instead:
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = EE.KeyWords.Find(SelectedKeyWord.ID);
myConditionTemplate.KeyWords.Add(NewKeyWord);
}

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