Sort order in Core Data with a multi-multi relationship - iphone

Say I'm modeling a school, so I have 2 Entities: Student and Class. For whatever reason, I want each class roster to have a custom sort order. In a simple relationship, this would mean giving Student a sortOrder attribute and just sorting the list by this number. Issue is, a Student might be order 3 in one Class and order 6 in another. How would I store these orderings in Core Data in a way that I can easily access them and sort my lists properly?
Student Class
classes <<--------->> students
^ ^
| |
unordered ordered
This diagram might help explain what I'm trying to do. The students "roster" I would want to be fetched in a specific order stored somewhere, which could be any ordering. Storing this ordering is what I'm not sure how to do in a way that's the most efficient. Creating a bunch of Order objects and trying to manage the links sounds like a lot of overhead, and it feels like there must be a better way.

If the ordering of students can be described by one or more NSSortDescriptors, you could create a fetched property on the Class entity that fetches the students and applies the sort descriptor. Alternatively, it may be easier (depending on your use case) to apply the sort descriptor(s) to the NSFetchedResultsController that you're using to deal with the class' students collection.
If you can't use an NSSortDescriptor, then you'll need an index attribute (or name of your choice) on the Student entity if there's only one ordering or a collection of Order entities describing the index in each ordering for each Student. You'll be responsible for maintaing these index values. Unfortunately, there's no easy way to do this in Core Data. It's just a lot of work.

Student <<->> StudentClass <<->> Class
StudentClass
----
studentID
order
classID
Then you can select as necessary.
For example, you have a student. Fetch all StudentClass where StudentID is student.studentID. You then have the order, as well as access to the Class.
You'll likely want to add some business logic to make your life easier. Also, if you're not already using it, take a peek at MOGenerator: https://github.com/rentzsch/mogenerator
EDIT: I'd really like to know why this is getting voted down. Comments would be much appreciated.

Related

What is the best method for L2E Join in following scenario?

Following are two tables:
Country >> CountryId, CountryName
City >> CityId, CityName, CountryId
I am using repository pattern to generate entity set from database. (example, repository.GetQuery<City>())
Now I want to write such a query that when I fetch City it also generates an populates for corresponding Country in the result set. So I can just access it like, city.Country.CountryName.
I know I can perform this by joining two entity sets, but that must be costly in performance. Probably, .Include<> may help me in achieving this. Any idea/ example to achieve this?
I'm going to assume, since you're using Entity Framework, that your City object has a navigational property of Country which points to the corresponding Country record.
As such, unless you specifically want to use lazy loading, you'll need to use Include. The good news is that you can do the includes inside of your repositories, and not have to write that code on the outside. An example of this can be found here.
Let me know if that works.

Design class diagram OrderItem entity

I have an Order, OrderItem and Stock entity. Basically, an order is created and then items can be added to the Order. An Order can have more than one item. Each item in the order is where the OrderItem comes into play.
My question is this: What attributes should I have for the order item class?
Currently I only have the primary key to identify it.
Should I have anything else?
I do not need any of the details for the items in the order as all the details for each item is in the Stock class.
Here is am image of what I am talking about:
What you 'need' to have will come down to wider requirements. Some things you might consider though:
You've included identifiers (keys) on the classes. You might also therefore want to include referentials (foreign keys) in Order Item - one each for Order.ordId & Stock.stkID respectively.
Do you need quantity? i.e. how many of each Stock item in each order? (e.g. 2 copies of "Lord of the Rings" if the stock items are books).
Date / time the order was placed?
Order status? (Confirmed/Shipped/Delivered/Cancelled etc.)?
Those are common things to find in such a scenario; which apply will depend on what you need to achieve.
hth.

Manually creating intermediate table in a many to many relationship for Core - Data

I'm currenty working with Core-data for an iPhone project.
But I'm a bit confused about one element.
With Core Data currently you do not need to create the intermediate table when creating many to many relationships (its all handled behind the scenes by core data)
But in my case I actually need some attributes on my many to many relationship!
For example
I have a table called Students
and another table called Lessons
a Student can be in many lessons
and a lesson can have many students
Now a standard many to many relationship will not work for me as I actually need to define more details on the join, i.e. StartDate and LeaveDate.
In a standard sql model for example my join table would be something like
StudentLessons (Studentid, LessonId, StartDate, LeaveDate )
I would need these properties as when i'm querying for information I will need the details from the join to filter my results.
How can I create this in core data and also filter for results?
I've seen folks say that you would actually create the StudentLesson entity manually in core data.
Now if I did this would I just have the attributes (Startdate, LeaveDate) and then a one to many relationship from the Student and then the Lessons table?
Student - > StudentLessons
Lesson - > StudentLessons
I guess I'm a bit confused on how I would go about making sure that the relationships and the content of the relationships are setup correctly. (i.e If I add an Student object to the StudentLessons - how would I then assign/add the Lesson.)
Sorry this is my first time playing with Core Data.
Takes a bit o getting used to when coming from a full on sql background.
You are absolutely right. The correct way to do this is to create a new entity like StudentLessons. Let's call it Attendance. It should have the startDate and endDate, and two relationships.
The relationship to the student can be many-to-many, unless it is foreseeable that startDate and endDate are always different for each student. One Attendance with its dates can have many students in it. One student can have several Attendance duties.
Student <<---->> Attendance
Clearly, the relationship to Lesson should be one-to-many. One Lesson can have different Attendance configurations, with different dates. But each Attendance belongs only to one Lesson.
Lesson <---->> Attendance
To address your question, you can make the Attendance attribute of Lesson non-optional (and vice versa), this way it will ensure that each Lesson has at least one Attendance with appropriate dates, and each Attendance has exactly one Lesson.
I think your can remove the link between Student and Lesson. Just assign an Attendance rather than a lesson. If you want a Lesson assigned to a Student without dates, just allow Attendance to have NULL as those properties.
TheTiger,
Just because Core Data will create a join table for you, that doesn't mean you have to use it. Maintaining which student succeeds with which lesson is just the same except you will create the intermediate entity and then use the appropriate setters to build the relationships.
You will have to use more key paths and do relationship prefetching but those are straightforward to do.
Andrew

No-sql relations question

I'm willing to give MongoDB and CouchDB a serious try. So far I've worked a bit with Mongo, but I'm also intrigued by Couch's RESTful approach.
Having worked for years with relational DBs, I still don't get what is the best way to get some things done with non relational databases.
For example, if I have 1000 car shops and 1000 car types, I want to specify what kind of cars each shop sells. Each car has 100 features. Within a relational database i'd make a middle table to link each car shop with the car types it sells via IDs. What is the approach of No-sql? If every car shop sells 50 car types, it means replicating a huge amount of data, if I have to store within the car shop all the features of all the car types it sells!
Any help appreciated.
I can only speak to CouchDB.
The best way to stick your data in the db is to not normalize it at all beyond converting it to JSON. If that data is "cars" then stick all the data about every car in the database.
You then use map/reduce to create a normalized index of the data. So, if you want an index of every car, sorted first by shop, then by car-type you would emit each car with an index of [shop, car-type].
Map reduce seems a little scary at first, but you don't need to understand all the complicated stuff or even btrees, all you need to understand is how the key sorting works.
http://wiki.apache.org/couchdb/View_collation
With that alone you can create amazing normalized indexes over differing documents with the map reduce system in CouchDB.
In MongoDB an often used approach would be store a list of _ids of car types in each car shop. So no separate join table but still basically doing a client-side join.
Embedded documents become more relevant for cases that aren't many-to-many like this.
Coming from a HBase/BigTable point of view, typically you would completely denormalize your data, and use a "list" field, or multidimensional map column (see this link for a better description).
The word "column" is another loaded
word like "table" and "base" which
carries the emotional baggage of years
of RDBMS experience.
Instead, I find it easier to think
about this like a multidimensional map
- a map of maps if you will.
For your example for a many-to-many relationship, you can still create two tables, and use your multidimenstional map column to hold the relationship between the tables.
See the FAQ question 20 in the Hadoop/HBase FAQ:
Q:[Michael Dagaev] How would you
design an Hbase table for many-to-many
association between two entities, for
example Student and Course?
I would
define two tables: Student: student
id student data (name, address, ...)
courses (use course ids as column
qualifiers here) Course: course id
course data (name, syllabus, ...)
students (use student ids as column
qualifiers here) Does it make sense?
A[Jonathan Gray] : Your design does
make sense. As you said, you'd
probably have two column-families in
each of the Student and Course tables.
One for the data, another with a
column per student or course. For
example, a student row might look
like: Student : id/row/key = 1001
data:name = Student Name data:address
= 123 ABC St courses:2001 = (If you need more information about this
association, for example, if they are
on the waiting list) courses:2002 =
... This schema gives you fast access
to the queries, show all classes for a
student (student table, courses
family), or all students for a class
(courses table, students family).
In relational database, the concept is very clear: one table for cars with columns like "car_id, car_type, car_name, car_price", and another table for shops with columns "shop_id, car_id, shop_name, sale_count", the "car_id" links the two table together for data Ops. All the columns must well defined in creating the database.
No SQL database systems do not require you pre-define these columns and tables. You just construct your records in a certain format, say JSon, like:
"{car:[id:1, type:auto, name:ford], shop:[id:100, name:some_shop]}",
"{car:[id:2, type:auto, name:benz], shop:[id:105, name:my_shop]}",
.....
After your system is on-line providing service for your management, you may find there are some flaws in your design of db structure, you hope to add one column "employee" of "shop" for your future records. Then your new records coming is as:
"{car:[id:3, type:auto, name:RR], shop:[id:108, name:other_shop, employee:Bill]}",
No SQL systems allow you to do so, but relational database is impossible for this job.

How to sort related entities with eager loading in ADO.NET Entity Framework

Greetings,
Considering the Northwind sample tables Customers, Orders, and OrderDetails I would like to eager load the related entities corresponding to the tables mentioned above and yet I need ot order the child entities on the database before fetching entities.
Basic case:
var someQueryable = from customer in northwindContext.Customers.Include("Orders.OrderDetails")
select customer;
but I also need to sort Orders and OrderDetails on the database side (before fetching those entities into memory) with respect to some random column on those tables. Is it possible without some projection, like it is in T-SQL? It doesn't matter whether the solution uses e-SQL or LINQ to Entities. I searched the web but I wasn't satisfied with the answers I found since they mainly involve projecting data to some anonymous type and then re-query that anonymous type to get the child entities in the order you like. Also using CreateSourceQuery() doesn't seem to be an option for me since I need to get the data as it is on the database side, with eager loading but just by ordering child entities. That is I want to do the "ORDER BY" before executing any query and then fetch the entities in the order I'd like. Thanks in advance for any guidance. As a personal note, please excuse the direct language since I am kinda pissed at Microsoft for releasing the EF in such an immature shape even compared to Linq to SQL (which they seem to be getting away slowly). I hope this EF thingie will get much better and without significant bugs in the release version of .NET FX 4.0.
Actually I have Tip that addresses exactly this issue.
Sorting of related entities is not 'supported', but using the projection approach Craig shows AND relying on something called 'Relationship Fixup' you can get something very similar working:
If you do this:
var projection = from c in ctx.Customers
select new {
Customer = c,
Orders = c.Orders.OrderByDescending(
o => o.OrderDate
)
};
foreach(var anon in projection )
{
anon.Orders //is sorted (because of the projection)
anon.Customer.Orders // is sorted too! because of relationship fixup
}
Which means if you do this:
var customers = projection.AsEnumerable().Select(x => x.Customer);
you will have customers that have sorted orders!
See the tip for more info.
Hope this helps
Alex
You are confusing two different problems. The first is how to materialize entities in the database, the second is how to retrieve an ordered list. The EntityCollection type is not an ordered list. In your example, customer.Orders is an EntityCollection.
On the other hand, if you want to get a list in a particular order, you can certainly do that; it just can't be in a property of type EntityCollection. For example:
from c in northwindContext.Customers
orderby c.SomeField
select new {
Name = c.Name,
Orders = from o in c.Orders
orderby c.SomeField
select new {
SomeField = c.SomeField
}
}
Note that there is no call to Include. Because I am projecting, it is unnecessary.
The Entity Framework may not work in the way you expect, coming from a LINQ to SQL background, but it does work. Be careful about condemning it before you understand it; deciding that it doesn't work will prevent you from learning how it does work.
Thank you both. I understand that I can use projection to achieve what I wanted but I thought there might be an easy way to do it since in T-SQL world it's perfectly possible with a few nested queries (or joins) and order bys. On the other hand seperation of concerns sounds reasonable and we are in the entity domain now so I will use the way you two both recommended though I have to admit this is easier and cleaner to achieve in LINQ to SQL by using AssociateWith.
Kind regards.