Core Data: How to design a tree data structure from one core data entry - iphone

I am struggling with designing a coreData model where I have only one type of entry called "To-Do". Each To-Do entry has either 0, 1, 2, ... , or n relationships to other (sub) entries just like To-Do. So the relationships between the To-Do entries design a tree structure with an undefined number of child nodes. The following graphic should illustrate the case (E = core data entry):
E
/|\
/ | \
E E E
/ \
/ \
E E
/|\
E E E
My guess was to model that data like illustrated in the following graph. I didn't choose the inverse relationship because Xcode made a many-to-many relationship out of it which doesn't match the tree design.
Also I saw in the data model inspector something called "parent entry". So I started to believe I might have to create a second entry named "To-Do-Child" with the same attributes and make the other entry to the parent entry. The manual tells me that this might be the wrong path to go...
Questions:
How can I model this approach within the core data model file? Is one of the ones mentioned correct?
How will I be able to fetch all To-Do entries of a specified parent node? Since they arise from the same entry I have problems to address the exact To-Do subtree I want.

I think you need a relationship of parent (destination entity is your to do entity) which serves as the destination for the inverse relationship.
Entries at the top of the tree have nil value for this relationship.
For any to-do item, the set returned from the childToDos relationship will hold all the children. It doesn't matter that these are of the same class.

Related

One-to-many different entity types

I'm learning nest.js with postgresql and I'm stuck on the one subject. Let's suppose I have three entities: entity A, B and C.
I want one of the field from the entity C to reference either to A or B.
At this moment I could set two different columns, where one refers (as one to many) to entity A, and another column to entity B.
Is there any way I could sort it out having only one column for that?
Like
#One-To-Many(ref to A | B)

Remove entities and remove relationships on Entity framework

I´m using EF databaseFrist and creating a model, now having a problem trying to understand how to delete an entity or a relationship.
Lest say a have and Table "A" and a Table "B", and a "a_b" table that relates A and B by id (many to many), a_b only has id_A and id_B, so there is no entity a_b created on the model. A has a list<B> and B has a list<A>, i need to know how can i perform the next functions:
-Remove all B entities related to A, it means delete the rows of B.
-Remove only the relationships of A to B, so all entities still exist on DB but they are dissociated.
-Delete A and remove all B related as well (remove entities from DB).
-Delete A and preserve all B entities.
-How will it change if a_b has any other property so it becomes an entity
thanks for your time.
pd: I´m using Lambda syntax.
You can tell EF on DB First model creation to expose all primary and foreign-key properties in the entities. What it means to you is that you can query separately by querying for child objects to a parent by using the foreign-key property of the child object linked to the parent object's primary key. You can delete each child object to the parent by the child's primary-key property value to remove the relationship between parent and child. You can delete the parent if no child object is linked to the parent. That's if one is doing things normally in a deletion process using EF where one takes complete control of the deletion process.
So, you can kind of do something like that.

How to use DBContext.Add/Attach (using EF CodeFirst 4.1) with nested opbjects

Problem: When adding an object "Order" to my dbcontext, all nested objects of the order gets "readded" to the database, though the nested objects is static data and only a reference shoudl be added in the database.
Example:
The database holds 0 orders, and 3 items.
I add one order with 2 items.
Now the database hold 1 order, and 5 items. The two items in the order has been "readded" to the database, even though the items had the right primary keys before db.SaveChanges().
I realize that i may be able to attach the existing items to the dbcontext before saving changes, but is that really the only way to go? Can't EF figure out that to item already exists when the primary key matches an existing item?
Does anyone know if this is different in the new version of EF CodeFirst?
No EF cannot figure if entities are existing one or new one - both Add and Attach commands are graph oriented operations. You call them on one entity in the graph and they traverse all relations (and their relations and so on) and perform the operation for them as well.
You must figure correct state of each entity in the graph for example by using:
dbContext.Orders.Add(newOrder);
foreach(var item in newOrder.Items) {
dbContext.Entry(item).State = EntityState.Unchanged;
}
dbContext.SaveChanges();
You can use the reverse operation by calling Attach(newOrder) and set the order to Added state. The main difference will come with independent associations (for example many-to-many relations). The first approach will correctly add new relation between order and each item whereas second will not unless you manually set each relation to Added state (and changing state for relations is more complex).

Entity Framework many-to-many question

Please help an EF n00b design his database.
I have several companies that produce several products, so there's a many-to-many relationship between companies and products. I have an intermediate table, Company_Product, that relates them.
Each company/product combination has a unique SKU. For example Acme widgets have SKU 123, but Omega widgets have SKU 456. I added the SKU as a field in the Company_Product intermediate table.
EF generated a model with a 1:* relationship between the company and Company_Product tables, and a 1:* relationship between the product and Company_Product tables. I really want a : relationship between company and product. But, most importantly, there's no way to access the SKU directly from the model.
Do I need to put the SKU in its own table and write a join, or is there a better way?
I just tested this in a new VS2010 project (EFv4) to be sure, and here's what I found:
When your associative table in the middle (Company_Product) has ONLY the 2 foreign keys to the other tables (CompanyID and ProductID), then adding all 3 tables to the designer ends up modeling the many to many relationship. It doesn't even generate a class for the Company_Product table. Each Company has a Products collection, and each Product has a Companies collection.
However, if your associative table (Company_Product) has other fields (such as SKU, it's own Primary Key, or other descriptive fields like dates, descriptions, etc), then the EF modeler will create a separate class, and it does what you've already seen.
Having the class in the middle with 1:* relationships out to Company and Product is not a bad thing, and you can still get the data you want with some easy queries.
// Get all products for Company with ID = 1
var q =
from compProd in context.Company_Product
where compProd.CompanyID == 1
select compProd.Product;
True, it's not as easy to just navigate the relationships of the model, when you already have your entity objects loaded, for instance, but that's what a data layer is for. Encapsulate the queries that get the data you want. If you really want to get rid of that middle Company_Product class, and have the many-to-many directly represented in the class model, then you'll have to strip down the Company_Product table to contain only the 2 foreign keys, and get rid of the SKU.
Actually, I shouldn't say you HAVE to do that...you might be able to do some edits in the designer and set it up this way anyway. I'll give it a try and report back.
UPDATE
Keeping the SKU in the Company_Product table (meaning my EF model had 3 classes, not 2; it created the Company_Payload class, with a 1:* to the other 2 tables), I tried to add an association directly between Company and Product. The steps I followed were:
Right click on the Company class in the designer
Add > Association
Set "End" on the left to be Company (it should be already)
Set "End" on the right to Product
Change both multiplicities to "* (Many)"
The navigation properties should be named "Products" and "Companies"
Hit OK.
Right Click on the association in the model > click "Table Mapping"
Under "Add a table or view" select "Company_Product"
Map Company -> ID (on left) to CompanyID (on right)
Map Product -> ID (on left) to ProductID (on right)
But, it doesn't work. It gives this error:
Error 3025: Problem in mapping fragments starting at line 175:Must specify mapping for all key properties (Company_Product.SKU) of table Company_Product.
So that particular association is invalid, because it uses Company_Product as the table, but doesn't map the SKU field to anything.
Also, while I was researching this, I came across this "Best Practice" tidbit from the book Entity Framework 4.0 Recipies (note that for an association table with extra fields, besides to 2 FKs, they refer to the extra fields as the "payload". In your case, SKU is the payload in Company_Product).
Best Practice
Unfortunately, a project
that starts out with several,
payload-free, many-to-many
relationships often ends up with
several, payload-rich, many-to-many
relationships. Refactoring a model,
especially late in the development
cycle, to accommodate payloads in the
many-to-many relationships can be
tedious. Not only are additional
entities introduced, but the queries
and navigation patterns through the
relationships change as well. Some
developers argue that every
many-to-many relationship should start
off with some payload, typically a
synthetic key, so the inevitable
addition of more payload has
significantly less impact on the
project.
So here's the best practice.
If you have a payload-free,
many-to-many relationship and you
think there is some chance that it may
change over time to include a payload,
start with an extra identity column in
the link table. When you import the
tables into your model, you will get
two one-to-many relationships, which
means the code you write and the model
you have will be ready for any number
of additional payload columns that
come along as the project matures. The
cost of an additional integer identity
column is usually a pretty small price
to pay to keep the model more
flexible.
(From Chapter 2. Entity Data Modeling Fundamentals, 2.4. Modeling a Many-to-Many Relationship with a Payload)
Sounds like good advice. Especially since you already have a payload (SKU).
I would just like to add the following to Samuel's answer:
If you want to directly query from one side of a many-to-many relationship (with payload) to the other, you can use the following code (using the same example):
Company c = context.Companies.First();
IQueryable<Product> products = c.Company_Products.Select(cp => cp.Product);
The products variable would then be all Product records associated with the Company c record. If you would like to include the SKU for each of the products, you could use an anonymous class like so:
var productsWithSKU = c.Company_Products.Select(cp => new {
ProductID = cp.Product.ID,
Name = cp.Product.Name,
Price = cp.Product.Price,
SKU = cp.SKU
});
foreach (var
You can encapsulate the first query in a read-only property for simplicity like so:
public partial class Company
{
public property IQueryable<Product> Products
{
get { return Company_Products.Select(cp => cp.Product); }
}
}
You can't do that with the query that includes the SKU because you can't return anonymous types. You would have to have a definite class, which would typically be done by either adding a non-mapped property to the Product class or creating another class that inherits from Product that would add an SKU property. If you use an inherited class though, you will not be able to make changes to it and have it managed by EF - it would only be useful for display purposes.
Cheers. :)

iPhone Development - Query related records using CoreData

I have a case where i have three entities with one-to-many and one-to-many relationships:
Entity A (Entity B relationhip),
Entity B (Entity A relationship, Entity C relationship),
Entity C (Entity B relationhip)
I have the reference of Entity A, and now i want to fetch all the related Entity C records. How can i do that? (with least amount of code)
Edit: Here's another way to put it.
Can we perform joins with CoreData. For example, (and this is a very crude example), We have a following entity-relationship:
Grand Parent (1)---(m) Parent
Parent (1)---(m) Child
So, now if i have "Albert" the Grand Parent, and i want to get all his grand children, how can i do that?
In case someone else stumble across a similar situation, here's what worked for me:
NSArray *allFieldValues = [myEntityA valueForKeyPath:#"Entity B relationship.Entity C relationship.requiredFieldInEntityC"];
I was mainly interesting in reading the data of a single field in Entity C (that's linked to myEntityA object). The key concept here is that "don't think of CoreData as a 'database'".