Setting relationships in core data swift after context saved - swift

Working with a core data model and I am still new this. Right now I have a view controller that saves the relationship between 2 entities and it stays fine until I have to add another relationship into the primary core data entity. When I do this the relationship between the initial 2 relationships breaks and the tableview is no longer able to present the relationship and thus crashes. I know in order to set the relationship I need to insert it into the already existing context but how do I actually go about that without clearing out the previously set relationhip?
Let's say I have a entity named primary and one named secondary. The relationship between these two sets fine. When I try to set the relationship for the third entity the relationship between the secondary and primary clears out. The real problem is that I am actually passing the object I want to store the relationship into so when I do code similar to this:
passedObject?.relationhips = entity.relation
it isn't actually setting the relationship. Am I missing something? Do I have to insert something into the primary entity context outside of setting the relationship?

A really common core data crash is when you've updated your model but the app on the simulator has data that uses the old model and crashes. So after updating your modal it's a good habit to delete your app from the simulator before running again (although I think Apple made a change in iOS9 where your app will migrate the data automatically but I've not checked that).
If that's not the problem it would help a lot to see a screen grab of your model to see how relationships between your entities are set up.
Because you're new to core data, I'd check to see if the relationship type if 'to one' (the default) or 'to many' (to use if you want a connection between a set of entities instead of just one).

Always check core data subclasses after you have them created automatically by Core Data. Sometimes the setup is incorrect as was the case with my problem.

Related

Navigation Properties between Views in EF Code First

Is it possible to define navigation properties between Views in EF with code first? Please, note that I do not need any tool generating any code for me. I would like to know whether or not this can get done and the logic behind this.
Suppose you have a project in which you will only work with views. No data will be created, updated or deleted (at least by you). All you need to do is queries and all you have are views.
Suppose now a second scenario in which you can also have tables, but your purpose is only to visualize data (you will treat them as views). However, there is not always a foreign key referencing the primary key of the parent table in relationships.
My question is: Can I define navigation properties in these scenarios? Or do I have to relay on joins only?
Thanks!
I'm working on this myself. Everything I'm reading indicates you have to manually edit the .edmx files so that the views are considered tables and manually add the nativation properties yourself. Downside is if you resync against the database you have to repeat the process all over again.
Re:
https://social.msdn.microsoft.com/Forums/en-US/dcbdfe52-6ba7-4e75-94aa-51c88b57635c/adding-navigation-property-to-a-view?forum=adodotnetentityframework

Can I create an entity by default with core data?

I'm creating a project in Xcode 7.3.1 that uses core data to store a "UserProfile" entity with three attributes. I have set up default values for these attributes but is there any way that I can set it so that a UserProfile entity is created the first time the app is run by default? I will only ever need one of these entities but I will need to access and modify the attributes as the app is used.
Two things about this:
No, there is no way to have an instance of a Core Data entity created by default. Your code must create it.
If you will only ever have one instance, Core Data is a completely inappropriate tool. It makes no sense at all. Store the data in user defaults, or if you prefer, in a separate property list file.

Entity Framework Service Layer Update POCO

I am using the Service Layer --> Repository --> Entity Framework (Code-First) w/POCO objects approach, and I am having a hard time with updating entities.
I am using AutoMapper to map my Domain Objects to my View Models and that works good for getting the data, no how do I get that changes back into the database?
Using pure POCO objects, I would assume that there is no sort of change tracking, so I see my only option is to handle it myself. Do you just make sure that your View Models have the EXACT same properties as your Domain Objects? What if I just change a field or two on the View Model? Won't the rest of the fields on the Domain Object get overwritten in the database with default values?
With that said, what is the best approach?
Thanks!
Edit
So what I am stumbling on is this, lets take for example a simple Customer:
1) The Controller has a service, CustomerService, that calls the services GetCustmoerByID method.
2) The Service calls into the CustomerRepository and retrieves the Customer object.
3) Controller uses AutoMapper to map the Customer to the ViewModel.
4) Controller hands the model to the View. Everything is great!
Now in the view you do some modifications of the customer and post it back to the controller to persist the changes to the database.
I would assume at this point the object is detached. So should the model have the EXACT same properties as the Customer object? And do you have to make hidden fields for each item that you do not want to show, so they can persist back?
How do you handle saving the object back to the database? What happens if your view/model only deals with a couple of the fields on the object?
If you're using EF Code First, i.e: the DbContext API, then you still do have change tracking which is taken care of by your context class.
after making changes to your objects, all you have to do is call SaveChanges() on your context and that will persist the changes to your database.
EDIT:
Since you are creating a "copy" of the entity using AutoMapper, then it's no longer attached to your context.
I guess what you could do is something similar to what you would in ASP.NET MVC (with UpdateModel). You can get the original entity from your context, take your ViewModel (which may contain changed properties) and update the old entity, either manually (just modified properties), or using AutoMapper. And then persist the changes using context.SaveChanges().
Another solution would be to send the model entity as [part of] the ViewModel. This way, you'll have your entity attached to the container and change tracking will still work.
Hope this helps :)
You are absolutely right that with a detached object you are responsible for informing the context about changes in your detached entity.
The basic approach is just set the entity as modified. This works for scalar and complex properties but it doesn't work for navigation properties (except FK relations) - for further reading about problems with navigation properties check this answer (it is related to EFv4 and ObjectContext API but same problems are with DbContext API). The disadvantage of this approach is that all fields in DB will be modified. If you just want to modify single field you still have to correctly fill others or your database record will be corrupted.
There is a way to explicitly define which fields have changed. You will set the modified state per property instead of whole entity. It is little bit harder to solve this on generic approach but I tried to show some way for EFv4 and for EFv4.1.
I agree with #AbdouMoumen that it's much simpler to use the model entities at the view level. The service layer should provide an API to persist those entities in the data store (db). The service layer shouldn't dumbly duplicate the repository lawyer (ie: Save(entity) for every entity) but rather provide a high level save for an aggregate of entities. For instance, you could have a Save(order) in the service layer which results in updating more basic entities like inventory, customer, account.

Entity Framework - Foreign key constraints not added for inherited entity

It appears to me that a strange phenomenon is occurring with inherited entities (TPT) in EF4.
I have three entities.
1. Asset
2. Property
3. Activity
Property is a derived-type of Asset.
Property has many activities (many-to-many)
When modeling this in my EDMX, everything seems fine until I try to insert a new Property into the database. If the property does not contain any Activity, it works, but all hell breaks loose when I add some new activities to the new Property.
As it turns out after 2 days of crawling the web and fiddling around, I noticed that in the EF store (SSDL) some of the constraints between entities were not picked up during the update process.
Property_Activity table which links properties and activities show only
one constraint
FK_Property_Activity_Activity but
FK_Property_Activity_Property was
missing.
I knew this is an Entity Framework anomoly because when I switched the relationship in the database to:
Asset <--> Asset_Activity <--> Activity
After an update, all foreign key constraints are picked up and the save is successful, with or without activities in the new property.
Is this intended or a bug in EF?
How do I get around this problem?
Should I abandon inheritance altogether?
Not a but but a poor visual designer.
Its generally best to simply manage the Entity XML by hand.
No inheritance works well for many situations.
Basically I use the update from database in the visual designer but knowing that the designer has its quirks. I have simply used the update from database to stub out the basics of what I want. Then I go into the Entity XML my self and clean it up the way I want. Just of note Complex types are a pain with the designer. If you plan to use complex types get ready to learn your Entity XML well.

Can we use union of two sqlite databases with same tables for Core Data?

I have an iPhone Core Data app with a pre-populated sqlite "baseline" database. Can I add a second smaller sqlite database with the same tables as my pre-populated "baseline" database but with additional / complementary data such that Core Data will happily union the data from both databases and, ultimately, present to me as if it was all a single data source?
Idea that I had is:
1) the "baseline" database never changes.
2) I can download the smaller "complementary" sqlite database for additional data as and when I need to (I'm assuming downloading sqlite database is allowed, please comment if otherwise).
3) Core Data is then able to union data from 1 & 2. I can then reference this unified data by calling my defined Core Data managed object model.
Hope this makes sense.
Thanks in advance.
Core Data is designed to handle multiple data files via the – addPersistentStoreWithType:configuration:URL:options:error: method. This will allow you to combine all of the data files together and then access them via a single NSManagedObjectContext.
Your only issue, and it may not even be an issue for you, is that the store files cannot directly reference each other. Therefore you will need to reference data between files "manually" via unique identifiers. However I suspect you are already aware of that limitation.
Manual Relationships
The idea is that when both objects in a "relationship" are in one model and one file, Core Data does its magic and handles all of the referential integrity for you. However when they are in different files and/or models this doesn't happen automatically anymore.
The solution to this issue is to use a fetched property that looks up some unique identifier to retrieve the entity (or entities) that you want to be on the other side of the relationship. This will give you a "weak" relationship between files.
One thing to note though when doing this. The fetched property does not get updated automatically when something changes. This means when data changes that would cause that relationship to change, your application will not be automatically made aware of it and you will need to request that property again to get the updated relationship information.
Hopefully that makes it a bit clearer.
Co-existance of fetched properties and relationships
They can definitely co-exist but realize that they are two separate properties. If you want your controller code to see them as one, then I would suggest building a subclass for that entity and then adding a convenience method in there that hits both the relationship and the fetched property and then rolls them up into one NSArray or NSSet before returning it back to your controller code.
You can attach the downloaded database with ATTACH DATABASE statement and operate with unions of tables.