Core Data Inheritance - Manage Inverse relationships of subclasses - swift

I am new to CoreData environment and I'm trying to understand how it works.
In my project, I have a superclass VetExam whose subclasses are Examination, Treatments and Vaccination, which share the same attributes of their superclass and has a reference to Pet class. On the other hand, Pet class holds an array of reference of every class except of VetExam, which should only be used for Polymorphism (so that I can use VetExam object and create a single view for each type).
Based on this model, I've tried to create entities in CoreData, but it seems that I have to specify for each type the inverse relationship for each entity. This represent a problem since from VetExam entity side the relationship is of type Pet but on Pet side is To-Many for each type of Examination, which does not allow me to get the inverse reference of VetExam.
Since this explaination can easily be misunderstood, I will show you the visual representation of it.
The problem is in VetExam entity, whose Inverse attribute is not known.
Does anyone know how to deal with this type of situation?

A preliminary note on inheritance...
Class inheritance
AND
Entity inheritance
For the second, I highlight the note in the Apple Documentation:
Be careful with entity inheritance when working with SQLite persistent
stores. All entities that inherit from another entity exist within the
same table in SQLite. This factor in the design of the SQLite
persistent store can create a performance issue.
What this means is that Core Data framework creates one large table in the SQLite database that includes the parent entity and the child entities. Such a large table inherently contains inefficiencies. While this may seem convenient for you to manage now in your model editor and in your NSManagedObject subclasses, this may cause inefficiencies / performance issues in the long run if you expect your app to persist and retrieve large amounts of data in the four entities you mention.
Advice from others is very relevant here because four separate entities will in my humble opinion be easier to manage, rather than one parent entity and three child entities. You do not have to give up the class inheritance you’ve developed in your code if you choose this option.
So, to answer your question...
My logic:
Every Pet may have many instances of VetExam during its life, but each instance of VetExam is carried out on only one Pet?
If yes, then create a one-to-many relationship between Pet and VetExam -
Pet <—>> VetExam.
Whatever occurs during the VetExam is any combination of one Examination, Treatment and/or Vaccination. That is and in an attempt to be clear, the VetExam may optionally have an examination, but it may not have a treatment or a vaccination. This is likely to change for each VetExam, therefore this is directly related to the VetExam, not the Pet.
If yes, then create optional one-to-one relationships between VetExam and the entities Examination, Treatment and Vaccination.
VetExam <—> Examination
VetExam <—> Treatment
VetExam <—> Vaccination
In this model, each entity relationship detailed above has an inverse.
Finally, it might be worth noting that in this proposed model, the relationship between a Pet and all the examinations, treatments and vaccinations it receives during its lifetime is stored against PetExam, not directly against the Pet.

Related

What is included in DbContext model?

Description:
I've tried to separate certain domain segments into different DbContexts.
Each has several DbSets, but there are some DbSets that are shared, for example the UserProfile.
The reason for this separation is the speed at which the model is generated and the simplicity (less sets in an object, helps with intellisense).
However, I am not sure about what exactly belongs to the model that is generated.
Q1: Is every entity that is transitionally connected with the entities, for which a DbSet exists in a DbContext, included in the model?
Q2: If so, would that mean that performance-wise it serves no purpose to separate the domain into different contexts, since everything that is connected ends up in the model anyway, no matter which DbSets are stated in the DbContext?
Where can I find more information on how the model is generated? I've read a book on EntityFramework and CodeFirst and couldn't find that specific information...
Answering your first question: yes, all relations are modeled including the entities on both sides, so every entity that's connected by a navigation property to an included entity will also be included in the model regardless if there's a DbSet for it or not.
Entity Framework doesn't force you to create DbSets for all entities. This can be handy if you want to "restrict" child entities to only be accessible through their parents.
Regarding your second question: separating your contexts might still improve performance, if not all entities belonging to one context are reachable via navigation properties of entities belonging to the other context. There could be an additional cost associated with explicitly including more DbSets in a context, too.
You could read (some parts of) the Entity Framework source code, it's open-source and available on CodePlex to learn more about how the model is built.

What's an entity in entity framework?

In the tutorials im following for learning about the entity framework, they keep mentioning entities. I often see it gets used as a synonym for the dbsets<> in the database context class, but what's the literal meaning of it?
I already know how the entity framework works, I just dont understand the meaning of the word.
In Entity Framework an entity is largely equivalent to a class in the conceptual model (or the class model, which is mapped to the store model).
In domain model terms an entity is
An object that is not defined by its attributes, but rather by a thread of continuity and its identity.
(Source: Wikipedia)
That quite a mouthful for "an object with an identity", as opposed to a value object, like a DateTime or (maybe) an Address. A Customer is an entity, because it is identified by "who" he is. Two customers with the same name are still two customers.
So entities can loosely be defined as the "things" the business domain is about. The things both the customer/user and the system designer/developer talk about in ubiquitous language. And in EF those things are represented by classes.
So it's not the DbSet. The DbSet is a repository that provides entity objects.
I often see people referring to entities as models. I don't know the origin of this terminology (it seems to happen too often to be a coincidence), but I don't think it's correct. It's mostly confusing. The model in EF is either the store model or the conceptual model, so it's a collection of entities. A model can also be a view model that comprises any number of attributes of any number of entities.
Lets take a Person object for example and lets say the Person data is being posted to a database and its moving through the tiers
When its in my UI, I call it a Person Model or ViewModel.
When its in my business layer I call it a Person Business Object.
When its in my Data Layer, I call it a Person Entity.
Its the same data that is moving into different objects in different tiers. The entity is just the name of the object that is holding the Person data in the Data Access tier....
An entity is simply an object that represents some form of relational data. This is typically used for representing relational databases, but it is not confined to that. I suggest looking at http://msdn.microsoft.com/en-us/data/aa937709 for a brief overview of how the Entity Framework works.

How should I map relationships between multiple inheritance models?

I have an Eentity Framework model with a Table Per Hierarchy (Brand) and also a Table Per Type (Vehicle) inheritance like this:
(Vehicle and Brand are abstract classes).
So far so good, I can access derived entities on linq queries using Vehicle.OfType<> or Brand.OfType<> method.
Now, Brand entity is one to many related with Vehicle on my conceptual model, So the question is, how should I make relationships on EF model so I can keep using navigation properties between Vehicle and Brand but at the same time keep the consistency of the TPH inheritance on Brand?, my first approach was to relate only derived clases, like:
But if I do this, I have no access to Brand directly from Vehicle, so I would have to do a double relation (between derived and base), like:
This works for me now, but I still have a duplicated relationship somehow, is this right?, do you have a better approach?, am I'm making some silly mistake on my modelling?
It seems to me that the reason you are running into cross-linking in your model is because you are artificially separating Brand and Vehicle as top-level sibling entities. If you start with Brand, which seems essentially equivalent to Make, that becomes the true top-level entity. There is no need to separate Make for each vehicle type (car, motorcycle, truck, etc.); just introduce the entity Model between Make and Vehicle and I think that solves most of your cross-linking problems.
Then the relationships aren't strictly parent-child, but are more accurate as composition. So you have Make, which has a one-to-many composite relationship to Model, which in turn has a one-to-many composite relationship to Vehicle. Vehicles are instances of a Model, so there isn't really a parent-child relationship there either. With this structure, there is no need to branch the EF for each type of Vehicle, because that is just part of what is described by the Model entity.
I hope my answer is helpful and that I haven't missed any of the essential points of what you are trying to model-

owned and unowned relationships

What exactly is meant by owned and unowned relationships? These terms are often used in JPA/JDO documentation, but I haven't found a good definition of them.
In addition to Nix's anwser, in JPA this term sometimes is used in different meaning - relationship is said to be owned by an entity if that entity is an owning side of the relationship, i.e. a side which defines the state of the relationship to be persisted.
There tons of good definitions out there on Owned/Unowned Relationships.
Google App Engine Entity Relationships in JDO:
A relationship between persistent objects can be described as owned, where one of the objects cannot exist without the other, or unowned, where both objects can exist independently of their relationship with one another

Core Data entity inheritance --> limitations?

I thought I'll post this to the community. I am using coredata, and have two entities. Both entities have a hierarchical relationship. I am noticing quite a lot of duplicated functionality now, and am wondering if I should re-structure to have a base Entity which is abstract (HierarchicalObject), and make my entities inherit from them.
So the question is are there some limitations of this inheritance that I should take into account? Reading some of the posts out there, I see a few trade-offs, let me know if my assumptions are correct.
(Good) clean up structure, keep the HierarchicalObject functionality in one spot.
(Ok) With inheritance, both objects now end up in the same sqlite table (I am using Sqlite as the backend). So if the number of objects grow, search/sorting could take longer? Not sure if this is a huge deal, as the number of objects in my case should stay pretty static.
(not so good) With inheritance, the relationship could get more complicated? (http://www.cocoadev.com/index.pl?CoreDataInheritanceIssues)
Are there other things to take into account?
Thanks for your comments.
I think it's a mistake to draw to close a parallel between entities and classes. While very similar they do have some important differences.
The most important difference is that entities don't have code like a class would so when you have entities with duplicate attributes, your not adding a lot of extra coding and potential for introducing bugs.
A lot of people believe that class inheritance must parallel entity inheritance. It does not. As a long as a class descends from NSManagedObject and responds to the right key-value messages for the entity it represents, the class can have many merry adventures in it's inheritance that are not reflected in the entities inheritance. E.g. It's fairly common to create a custom base class right below NSManagedObject and the have all the subsequent managed object subclasses inherit from that regardless of their entities.
I think the only time that entity inheritance is absolutely required is when you need different entities to show up in the same relationship. E.g:
Owner{
vehical<-->Vehical.owner
}
Vehical(abstract){
owner<-->Owner.vehical
}
Motocycle:Vehical{
}
Car:Vehical{
}
Now the Owner.vehical can hold either a Motocycle object or a Car object. Note that the managed object class inheritance for Motocycle and Car don't have to be same. You could have something like Motocycle:TwoWheeled:NSManagedObject and Car:FourWheeled:NSManagedObject and everything would work fine.
In the end, entities are just instructions to context to tell it how the object graph fits together. As long as your entity arrangement makes that happen, you have a lot flexibility in the design details, quite a bit more than you would have in an analogous situation with classes.
I thought it would be useful to mention that the Notes app on iOS 10 uses inheritance in its Core Data model. They use a base entity SyncingObject, that has 7 sub-entities including Note and Folder. And as you mentioned all of these are stored in the same SQLite table which has a whopping 106 columns, and since are shared among all entities most are NULL. They also implemented the folder-notes one-to-many relation as a many-to-many which creates a pivot table, which might be a work-around for an inheritance problem.
There are a couple of advantages to using entity inheritance that likely outweigh these storage limitations. For example, a unique constraint can be unique across entities. And a fetch request for a parent entity can return multiple child entities making UI that uses fetched results controller simpler, e.g. grouping by accounts or folders in a sidebar. Notes uses this to show an "All Notes" row above the Folder rows which is actually backed by an Account.
I have had issues in the past with data migration of models that had inheritance - you may want to experiment with that and see if you can get it to work.
As you noted also, all objects go in one table.
However, as Core Data is managing an object graph, it is really nice to keep the structure the way you would naturally have it just modeling objects - which includes inheritance. There's a lot to be said for keeping the model sane so that you have to do less work in maintaining code.
I have personally used a fairly complex CD model with inheritance in one of my own apps, and it has worked out OK (apart from as I said having issues with data migration, but that has been so flakey for me in general I do not rely on that working any longer).