Need to convert SQL Query to Coredata Format - sql

SQL Query
select * from zchildren where zparent = 3586 OR zparent in (Select zid from zchildren where zparent = 3586)
I have tried few cases with $SUBQUERY but Still i am not getting any success. So how can i achieve this ?
Update
I have Table Name which is Children which has Parent which contains the ID of the same table ID , Its a Inverse Relationship now i want All the children which parent is '3586' and its all sub children
Update2
I am Attaching the screen shot
Now Few more points
Table Group has One-To-Many Relationship with Children
Table Children has Two Relationship
First which is Inverse to Group One-To-One
Second children relation which is Inverse to itself which is called Reflexive
Updated Question
Now suppose i have one Query i want to search from Children table where title is 'Medical' AND Parent is '3586'
Now This '3586' is parent id which is coming from Table Group And i can easily predicate this .
Problem
It Gives me children whose parent '3586' but i also want to search in the title of sub-children which are Reflexive of this parent ID , Means sub-children of children which came from parent '3586'.
I really need this solution. I can still update my question if any one is not clear in this question.

When tackling somewhat complicated Core Data issues, you really have to be a bit more accurate. Your code and your variable names are sloppy and wrought with mistakes.
In your SQL query you have an attribute parent (or "zparent"), but in the Core Data model it becomes an attribute rather than a relationship. (Were you perhaps thinking of modeling ids? That would indicate that you are still trapped in relational database thinking and have not fully grasped the concept of the object graph yet. Forget about ids and think in relationships instead.)
You need a reverse relationship to children, so this cannot be the same relationship. Calling the entity "Children" is confusing because 1) you are using the plural for a singular object and 2) you are calling both parent and children "Children". You also misspell "Children" as "Childran", potentially leading to all sorts of errors.
Instead, let me suggest the entity name Person. A person can have one or more parents (or is it only one?) and one or more children both of which are also of type Person, resulting in a many-to-many relationship:
Person - parents <<----------------->> children - Person
If a person can only have one parent it if of course a many-to-one relationship.
Person - parent <------------------->> children - Person
You can then fetch a Person with idNumber 3586 (notice that using id is perhaps also a bad idea as it is a reserved word in some contexts). You can then access that person's children very succinctly:
person.children
That's really all there is to it.

Related

ADO.NET recurring results from relationships

I'm working on a project in ASP.NET MVC 5, with ADO.NET EF to generate data from the SQL server. I have several one-to-many relationships in the database. When I fetch data and project it to a local variable, e.g. var query = model.listFromDbChildTable.ToList(); where model.listFromDbChildTable is just entities loaded from the db. This is the lowest table in the relationship hierarchy.
So the thing is, and I am not sure why, every time I go to "locals" in VS, in debug mode, I can go deeper and deeper into my relations, for example, I am looking at a child table (department), and when I go to this child in locals, I see child has a relation with parent (above it), s I go to parent table, (I believe this is normal,) but when I'm at parent (table), again I can go to child table from there, and I am not going up one step back in the hierarchy, but so to say deeper, like a stair down all the time. So I go again to child, and child can go to parent again, every time with the same element. And I can redo this process many times?
So what is going on? Are my relations wrong or is this some normal procedure with locals in VS?
The following image shows two tables that participate in one-to-many relationship. The Course table is the dependent table because it contains the DepartmentID column that links it to the Department table.
Basically any link between two entities can be explored(Table in SQL ,class in EF)
In SQL you refer just a column in child table as key whereas in entity a property is create which has type of a class .
Like in below example, Course will have property name "Department" of type "Department" class as it depends on it (also a DepartmentId property).
you can read more in detail here on msdn..and Don't worry moving from SQL to Entity framework does give you small suprises :) .Hope it helps.
Parent Child Entity MSDN

Parent & Child FK'ing to same table

What is best practise when a parent & child table both FK to the same table?
Parent > Child(ren)
CommonAttributes: Sex, Age, Height, Weight
Is it better to directly reference the common table:
CommonAttributes > Parent(s) > Child(ren)
&
CommonAttributes > Child(ren)
Or use a reference table:
RefTable: CommonAttributes_Id, Parent_Id(null), Child_Id(null)
I think the first method works OK (with regards to EF) but it is a bit of a circular reference. Is it better to use a reference table to define the constraints?
There are several approaches to this and the one you need depends on your business needs.
First, can a child record have more than one parent? For instance you might be modelling an organizational structure where an employee can have two supervisors. If this is true, then you have a one to many relationship and need a separate table for this model to work.
If you are guaranteed to have only one parent per child (but each parent might have a parent (building a hierarchy), then you can model this is one table. The table structure would include the Primary key, say UserID and then a nullable column for the parent such as ParentUserID. Then you can create the foreign key to the field in the same table.
ALTER TABLE dbo.Mytable ADD CONSTRAINT FK_Mytable _UserPArent FOREIGN KEY (ParentUserD) REFERENCESdbo.Mytable (UserID)
If you want to build a hierarchy in a query, you then use a recursive CTE to get it. See example here:
https://msdn.microsoft.com/en-us/library/ms186243.aspx
Another time you might want to build a separate table for the child parent relationship is if only a small portion of teh records in the main table would have parent child relationships. For instance suppose you had a people table that stored, sales reps and customers. Only sales reps would have a parent child relationship. So you would want a separate SalesRepHierarchy table to store it which woudl make querying more straightforward.
While in general you woudl want to create hierarchies in a recursive CTE, there are special cases when it might be faster to pre calculate the hierarchies. This is true if the hierarchy is frequently queried, the CTE performance is slow and you have control over how the hierarchy is built (preferably through an import of data only) and if it changes fairly rarely (you would not want to be rebuilding the hierarchy every minute, but a once a day import can be accommodated. This can greatly speed up and simply querying for the whole hierarchy, but is not recommended if the parent child relationships are created and changed constantly through the application.

SQL database design

I am making a database for a program where i am supposed to model some relations in the family.
ex:
X is father to Y , Y is son to X
So , i have a Members table with all info about each member so i thought about making a many to many relation between the Members table and itself so that the Member_Member bridge table will be having the columns "FK_FromID , FK_ToID" as composite key (is this correct ?) and "FK_RelationType" as a foreign key to RelationTypes table which will have the relation type "Father,mother, son,daughter" , and two relations going as one to many from the Members table to these two foreign keys
My problem is : when deleting if i choose cascading then i will make cycles because if i delete a member then there will be two delete passes to related records in Member_Member bridge , knowing that in the program whenever i insert a father relation i will insert a son relation as well in the Member_Member table , is there a way or a workaround possible to enable cascading so that whenever i delete a member i will delete the related records in Member_member regardless of being recorded in either a to or a from foreign key column
So, i don't know what to do , is this a correct design in the first place or what ? , what should i do about cycling , also what do you think a better design for the same problem should be knowing that i need to specify what kind of relation between the two parties
Thanks a lot for any help , and sorry for bad english
Bishoy
SQL does not handle "network" problems like this very well.
The member-member bridge table is a terrible name. It's a "member-parent" (or "parent-child") bridge. Bridge tables should not have a "composite key". Bridge tables have a surrogate key (just a sequential number) and a pair of FK references to other tables. The two FK's should have names like "member" and "parent" to make it perfectly clear what the relationship is in this table.
Everyone has a parent. Not everyone has children. Some parents will not have parents in this database; they're the "top parents".
It's easiest if the top parents have rows in the parent-child bridge with a parent FK of NULL. That way you avoid super-complex outer-joins -- every member has at least one member-parent row; ideally two.
You will find many "cycling" issues since relationships are transitive.
Note that you can't -- in a single standard SQL query -- find all members of the family, or all parents back to the top of the family, or all children and grand-children. There are SQL extensions that make this possible, but the standard doesn't handle it well.
The cascading delete doesn't work out well because the relationships in a family are directed in two ways (parent to children, child to parents), but SQL only has one kind of direction (FK reference).
You can try to assure that every member MUST have at least one (and at most two) rows in "member-parent" and the delete of a member deletes the two rows in "member-parent" and the keys have the proper names, you might make parts of this work.
Note that when you delete a member, this will break their parent relationships. You delete the member-parent row. That's good. What about their children? The other rows which have member-parent referring to this deleted parent are now broken. What does this mean? What should be done?
There's no standard answer. Removing rows from a connected graph leaves elements
unconnected. You have to work out some sensible rules for that.
Since SQL does not do this well, all designs will seem to have problems.
Assuming each member can only have one mother and one father, you would be able to derive all the relationships by simply keeping a mother_id and father_id field in the members table.
However this would only work if your database will not have missing information. For example, if member X is the brother of member Y, there would be no way to know this unless the parents of X and Y are stored in the database.
If your database will not be having missing information, the above might be easier to manage data integrity. Queries might get a bit complex however.
The member_member bridge you suggested has one serious problem since it implies a direction of the relationship, so that if X is the father of Y, Y is also the son of X. You suggested to define the relationship twice in both directions, but in general this is not recommended. This is a form of data duplication, and you can struggle to enforce referential integrity with duplication of data. Remember that the DBMS does not know that X is father of Y is the same as Y is the son of X.
I am aware that this is not a complete answer, but just a few observations. I totally agree with S.Lott's answer as in there is no standard way to "solve" this with relational databases.

What are Parent-Child relationships?

What is the parent and what is the child in a sql relationship?
In my case, I have a part (Say screw), and product material. For argument's sake, a product material (eg steel) can only belong to one part (but not in the real world). So this is 1:n. The part will have its pk as a fk in the ProductMaterial table.
Which is parent and which is child in this case?
Relational databases such as SQL actually have no concept of parent/child relationships - that is an interpretation that you as a programmer put on the data. There are architectures that explicitly state and use such relationships, such as heirarchical (and to a certain extent OO) databases.
You can interpret a 1:n relationship in database this way: A child is always that model which holds the foreign key as this indicates where it belongs to.
Of course if you have self referencing models/tables you have to look at it in a different way.
In this case, Part is parent and ProductMaterial is child.
A parent can have unlimited numbers of children (scary thought - 2 is enough for me!), whereas a child can have only a limited number of parents - and in DB terms, only 1!
Usually in a one-to-many relationship, it's the "one" record that is the parent, and the "many" records that are the children.
Of course, in some cases it doesn't make any sense to talk about a parent-child relationship. In your example it makes some kind of sense at least. In other examples you may even find the opposite, where a child has many parents, but then it's not very useful to describe it that way.
Another way to look at this, in addition to what David M. said, is in terms of an ORM implementation (such as Linq to SQL). You have two entities, Part and ProductMaterial. Each part entity has a set of ProductMaterial entities (children entities or an EntitySet). Each ProductMaterial entity has zero or one Part entity (parent entity or an EntityRef).
Randy
I would say that any table which has a one to many relationship with one or more other tables can be considered a parent to those other tables. Self joining? An ambiguous term which I don't think anyone understands.
'Product' is parent and 'Product material' is child in Product_ProductMaterial relationship or association.
If you delete a child, parent can live and continue life. If you delete parent, child become orphan or identityless which is not good. If A can not not be deleted before B is deleted, then A is parent and B is child.
If I guess right, in your case in Product_ProductMaterial relationship, if you delete Product, ProductMaterial will be assigned to no one, become orphan, identity crisis. But if you delete ProductMaterial, Product can still be there, no need identity support.
Sorry if my wordings are not good.

How would you model a "default child" flag with an ORM?

I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a many-to-many relationship between a parent class and its children.. I was wondering, what would be a simple way to express the concept "one of the children is the default/main one"?
For example, I'd need to persist the following:
This Person instance has Address X and Y, the main one is Y.
I saw this implemented using a "middle" class like "PersonAddressRelation" that would contain "Person", "Address" and the "main" flag, but I think it looks a bit cumbersome.. Is there a better way?
The simplest way would be to have a join table, PersonAddressRelation, and also a DefaultAddress column on the Person table that keys to the Address table.
A couple of remarks.
M:N relationships don't specify 'parent' and 'child', as there's no parent nor a child: there are simply two entities having an m:n relationship via a 3rd entity (the intermediate entity).
'Address' is in general not a valid entity type, as semantically it has no identity, similar to a 'name' has no identity (first name, last name). You'll see this when you look at re-using an entity instance of type Address: you won't do that in general. (though you will re-use a Customer entity instance for example, when the customer has multiple orders)
You want to specify an attribute on the M:N relationship (default), as it belongs there. This means that the relationship itself forms an entity (which is the intermediate entity, often it has just two FK fields forming the PK). This is called an 'objectified relationship', as the relationship itself is seen as an entity. Other examples of this are Employee m:n Department and you want to specify the StartDate an employee started for a department the employee works for.
So in general: create the intermediate entity, as it in general should be there, and add the attribute there. In this particular case with Address, be really sure you are re-using Address instances among related entities (Person). If not, merge Address with Person OR if a person can have multiple addresses, create a simple 1:n relationship between Person - Address, to normalize it out, though don't be afraid to merge address data into the entity it is related to, as often address data is really not re-used (so your m:n relationship is really not there: there's no Address instance which is related to multiple person instances.