How do I model a multiplicity of 2 in EF - entity-framework

I have two situations where I would want something like this. In my model, I have a Message which concerns either one or two Persons. Furthermore, the message has an association with two Addresses, i.e. a from Address and a to Address.
In the first situation with the two Persons, I would like to specify an association between Message and Person multiplicity of 1---1..2 or specify two associations, one with 1---1 and the other with 1---0..1. However, I cannot (or don't know how to) set the multiplicity to two. I can imagine that it might be possible to set it to 1--* with a constraint set to maximum 2 (however I don't know how to do that).
By adding the two associations I feel a bit weird when I look at the Message side because both associations have a 1 there which would indicate a Person should have two Messages related to it. I might want something like 0..1 on the Message side for both associations with an xor constraint on them or something, but I don't know if that is good practise or even possible in EF.
For the second situation, the problem is quite similar, except that there is always a from Address and always a to Address. Setting the multiplicity 1--* doesn't seem right to me. Here I would imagine there should definitely be two associations, a from and a to association (which happen to both go to the Address entity). This however results in the same problem on the Message side of having two 1's or two 0..1's.
So my question is, how do I model this correctly in an EDM?
Thanks in advance.
Update 1:
To clarify the question, I will give a little background information on why I need such a model. I have to be able to create a message. In this message I have to specify whether it concerns one or two persons. Of these persons I specify the first name, last name and some other non-unique properties (two people can have the same name). I could dump all these properties in the Message entity (fname1, lname1, fname2, lname2), but that seems a bad idea. Hence the Person entity was born. However, this might look like a Person can be linked to many messages, but this is not the case. There can be two different persons with the same properties. There is no way of telling whether these persons are actually the same person in real life or not.
In the case of the addresses, a similar argument holds. Two addresses can be spelled a bit differently, but if I write them on a letter and mail it, they will both arrive at the same location (e.g. sesamestreet or sesamestr.). So I don't have one Address entity connected to multiple Messages. Again, the only reason Address is a separate entity, is because I have two of em with exactly the same properties.
From a database design point of view this might not make sense, from a class diagram perspective it might make a bit more sense. I was under the impression that the EDM in EF should not be like a database design, but more like a domain model, so I hope I did the right thing.
Update 2:
I just thought of what I think might be the best way in this case. Because there is virtually no difference between Person1 and Person2 I feel like making the association between Message and Person 1..* acceptable. The fact that many means two will be something for lower layers to handle. In the address case, the from and to are quite different. They are both addresses, but I don't feel I can make em a list. I could split the from and to address into separate entities and let them inherit from Address. Then associate Message with each of the subclasses. It might seem a bit overkill, but you could reason that a from address might at some point have different requirements than a to address and hence different properties.
I am not 100% happy though (especially with the address part). This solution might or might not be OK, but I feel like it avoids the core problem.

For the first problem (Message - Person):
The crucial question is: do you want person1 to be non-nullable? And person2?
The second alternative you sketched looks pretty okay to me considered that you require a message to have exactly 1 Person1 (say: creator of the message), so a non nullable property. Person2 (say: person who last updated the message) can be either null or linked to an existing person. Fine!
What you see from the person class perspective is that it has two associations (and 2 navigation properties, which you collapsed...) one for thos messages where a specific person (instance of person entity) is the creator of and one for those messages where this specific person was the last updater. Pretty Fine! Isn't it? This way you can query the model from the perspective of the message (give me all messages and also the persons of each message that created it and last updated it...) Or...query a person and collect all messages that this person created or was the last updater of...get it?
But all comes down to determining if you allow nullability for Person1 and Person2.
I didn't read your second question, but think it's more of the same. need some advice with that one too? Just call me.
Furthermore. If from a business / functional viewpoint it's enough to have two persons then alternative 2 is the way to go. If on the other hand you want a complete history of persons how updated the message and also the one who created it (this will always be exactly one) you end up with one navigation property Message.Creator (exactly one) and Message.Updaters (0 to many). You see? From the person's viewpoint they may be the creator of messages (0 to many) or updater of messages (0 to many).

Phew...Fortunately you saw the importance of decompiling the message entity into more logical and reusable entities like person, message and adress. In my humble opinion you should have this design ->
Hence the Person entity was born.
However, this might look like a Person
can be linked to many messages, but
this is not the case. There can be two
different persons with the same
properties. There is no way of telling
whether these persons are actually the
same person in real life or not.
This sounds so strange to me...Although there might be incorrect input e.g. two persons reflecting one real-life person but with typo's for instance. But still a person could have more messages or not... And when it's really not the case you can handle this in your business code to prevent a specific person to be coupled to more than one message...
**** Update *****
I should model it this way:

Related

Modeling many to many relations with postgreSQL

I work in cattle production and I am learning about database design with postgreSQL. Now I am working on an entity attribute relationship model for a database that allows to register the allocation of the pastures in which cattle graze. In the logic of this business an animal can be assigned to several grazing groups during its life. Each grazing group in turn has a duration and is composed of several pastures in which the animals graze according to a rotation calendar. In this way, at a specific time, animals graze in a pasture that is part of a grazing group.
I have a situation in which many grazing groups can be assigned to many animals as well as many pastures. Trying to model this problem I find a fan trap because there are two one-to-many relationships for a single table. According to this, I would like to ask you about how one can deal with this type of relationship in which one entity relates to two others in the form of many-to-many relationships.
I put a diagram on the problem.
model diagram
Thanks
Traditionally, using a link table (the ones you call assignment) between two tables has been the right way to do many-to-many relationships. Other choices include having an ARRAY of animal ids in grazing group, using JSONB fields etc. Those might prove to be problematic later, so I'd recommend going the old way.
If you want to keep track of history, you can add an active boolean field (to the link table probably) to indicate which assignment is current or have a start date and end date for each assignment. This also makes it possible to plan future assignments. To make things easier, make VIEWs showing only current assignment and further VIEWs to show JOINed tables.
Since there's no clear question in your post, I'd just say you are going the right way.

Deciding on class responsibility

I know this is an opinionated question. However it comes up often at work.
When creating methods it's often a struggle to know which class should be responsible.
e.g.
bool result = ProductService.CategoryHasSoldOutOfProducts(int categoryId)
vs
bool result = CategoryService.CategoryHasSoldOutOfProducts(int categoryId)
In my opinion, the CategoryService should be responsible, as the method is taking a categoryId and is specific to the Category.
Others at my work say the ProductService should be responsible as the method is dealing with if Products have sold out.
Just trying to develop a better understanding of service architecture and good process. I'm interested in other peoples explanations for why they would choose one over the other.
Thanks
Disclaimer - this is a purely IMHO answer. I am answering this in the spirit of having a design brainstorm.
Based on the OP, it seems the relationship between Category and Product is an optional one to many : Category (0..1) <--------> (*) Product.
Implementation wise, this means that the Category entity probably has a Container of Products, and the Product entity has a reference to a Category which may be NULL.
In this case, I agree with the decision to place CategoryHasSoldOutOfProducts under the responsibility of the Category entity. The method name clearly implies that the Category entity should be responsible for informing its API user on the status of its products.
There is another option, however: An association class/entity. The motivation behind this entity is to describe the relationship between two other entities.
In this case, you can have a functional association entity which we will call ProductContainment for the sake of this example.
ProductContainment will have no internal state, and will hold functions which are provided with Category and/or Product entities as parameters.
It is then the responsibility of the association entity to provide the implementation of functions which relate to how Category and Product relate to one another.
If you end up using ProductContainment - then CategoryHasSoldOutOfProducts should be one of its functions.
Since you're asking for opinions, here is mine:
(Disclaimer: That's probably something you cannot easily implement in the business world)
As you are using the term "class", I assume you want to have something object-oriented. The problem is, a service is nothing a valid object could be created from. Instead, it's just a namespace for functions.
Additionally it's very general. It's like calling a class "Manager". You can put possibly everything inside of it and this class has the potential to grow to have hundreds of functions.
My advice: Create small entities. Small enough to be created without the use of any setters, just by calling the constructor. If you notice your object needs more functionalities, create a decorator that is a little bit smarter and can do the work for you.
I would need a few more details about your environment to be more precise, but I guess in your case, you would have something like a Category class that contains products and knows when it's sold out. Just imagine you have a team of persons and everyone knows something. Ask the right guys to do the stuff and stay away from managers or services.

When to use Core Data relationships in Swift?

I've read through a bunch of tutorials to the best of my ability, but I'm still stumped on how to handle my current application. I just can't quite grasp it.
My application is simply a read-only directory that lists employees by their company, department, or sorted in alphabetical order.
I am pulling down JSON data in the form of:
Employee
Company name
Department name
First name
Last name
Job title
Phone number
Company
Company name
Department
Company name
Department name
As you can see, the information here is pretty redundant. I do not have control over the API and it will remain structured this way. I should also add that not every employee has a department, and not every company has departments.
I need to store this data, so that it persists. I have chosen Core Data to do this (which I'm assuming was the right move), but I do not know how to structure the model in this instance. I should add that I'm very new to databases.
This leads me to some questions:
Every example I've seen online uses relationships so that the information can be updated appropriately upon deletion of an object - this will not be the case here since this is read-only. Do I even need relationships for this case then? These 3 sets of objects are obviously related, so I am just assuming that I should structure it this way. If it is still advised to create relationships, then what do I gain out of creating those relationships in a read-only application? (For instance, does it make searching my data easier and cleaner? etc.)
The tutorials I've looked at don't seem to have all of this redundant data. As you can see, "company name" appears as a property in each set of objects. If it would be advised that I create relationships amongst my entities (which are Employee, Company, Department), can someone show me how this should look so that I may get an idea of what to do? (This is of course assuming that I should use relationships in my model.)
And I would imagine that this would be the set of rules:
Each company has many or no departments
Each department has 1 or many employees
Each employee has 1 company and 1 (or no) department
Please let me know if I'm on the right track here. If you need clarification, I will try my best.
Yes, use relationships. Make them bi-directional.
The redundant information in your feed doesn't matter, ignore it. If you received partial data it could be used to build the relationships, but you don't need to use it.
You say this data comes from an API, so it isn't read-only as far as the app is concerned. Worry more about how you're going to use the data in the app than how it comes from the server when designing your data model.

Entity Framework and One to Many Relationships not saving right

I worked with Entity Framework several years ago, and this may just be me being a bit rusty. I have detached entities, that in turn have multiple child entities. In my case it's a person entity and each person has multiple addresses.
myPerson.FirstName="update first name";
//assuming they already have an address in the first entry
//with appropriate primary keys and foreign key ids, I could do:
myPerson.Addresses.First().Line1="update line 1";
myPerson.Addresses.Add(new Address(){line1="weee",line2="aaaa" postal="12345", type="work"});
myDb.Person.Attach(myPerson);
myDb.Entry(myPerson).State=EntityState.Modified;
myDb.SaveChanges();
When I do a scenario like this, I get what I expect with first name. It updates the first name, and as expected actually blanks out all other fields (LastName, Birthday etc etc) in the above code. It doesn't however create the new address for the person, nor does it update the existing address.
I don't recall it requiring extra work for the database context to know how to update the related entities associated with the person above. In my google searches I seem to be hearing the story that I need to do a considerable amount of work loading collections from the db and then going to town that way. I hope that isn't the case.
The key part of the code you pasted are these lines...
myDb.Person.Attach(myPerson);
myDb.Entry(myPerson).State=EntityState.Modified;
The first line will attach the entire object graph to the context and set the state of each entity in this graph to Unchanged. The second line of code will set the state of just the root entity to Modified (the others, such as the Address entities, will remain in the Unchanged state). When the changes are saved, only the single entity will be updated.
Of course, this assumes that you are working with disconnected entities (using one context to fetch the object graph and another to perform the update). I assume you are as you are attaching the entity.
/* Rant On */
Disconnected entities is sadly something isn't handled very well in the EF space. You will find plenty of samples in books and blogs that attempt to address disconnected entities but these strategies quickly fall apart as you try to implement more advanced scenarios (such as object graphs including collections of related items).
/* Rant Off */

Copying entities in Core Data

I have a couple of Core Data entities... Student and Exam.
Now, the Exams is initially just one object per exam - Maths Exam 3, English Exam 2 etc.
There is a relationship between Students and Exams in my data model (a student can have several exams). But initially, the Exams are just floating free, and not attached to any students.
How would I make a copy of one of the exams and attach it to a student?
If I do something like:
[student addExamsObject:examObject];
...then I think it simply references the original exam to the student, rather than making a copy.
I need a copy because the Exam has a boolean 'hasTaken', which is YES when the student has taken the exam. But if I set that now, it will make it seem like all the students with that exam have taken it.
Clarification: I would rather not restructure my model. The data is taken from a couple of xml files, one each for Students and Exams, which are parsed into the Core Data store. For instance, an Exam object might look like this:
name:Maths 5
class-id:12
year-id:4
student-id:0
..with a Student object looking like
name: Dave
class-id:12
year=id:4
student-id:222
Various rules are meant to guide which exams get attached to which students... for instance if all the Exam's ids are 0 then all students take the exam. If class-id and year-id match, and student-id is 0, then the Exam gets added to students with the same class and year. If the student-ids match, then just that student takes the Exam. etc etc.
I cannot change the way the xml is outputted from the server.
Another issue is that Exam has too-many relationship to a Question entity... in other words, the questions in the Exam. And I have to store answers to the questions that each student gives in an exam.
Edit: I wish people would try to answer my question rather than tell me to restructure my whole program. There are reasons why the data model has been structured like it is.
Edit2: Maybe I will have restructure....
Exam shouldn't have a hasTaken property. Think about it in the real world. An Exam would not know about who has taken it because many people could have taken it. The instance of taking an exam, then, should be a first-class concept in your model.
Consider this:
Exam has many TakenExams, TakenExams belongs to Student http://yuml.me/6627495d
Now the concept of taking an exam is a real object, you can then model assocation metadata as well, such as dateTaken, score, and so on.
Also remember that Core Data expects you to have all of your inverse associations set up as well.
You don't usually copy an entity. (I'm not sure what happens if you call copy on an NSManagedObject... it's not explained in the documentation, as far as I know. Experts can correct me. )
Just create another entity, or write a method which does just that.
I think another way is to make many-to-many relationships between Exam and Student:
create relationships in Exam called studentsToTakeThisExam and studentsWhoTookThisExam.
create relationships in Student called examsToTake and examsAlreadyTaken.
and set up the inverse relationships accordingly.
I would not argue (as You requested) if your modeling is correct or not. The procedure to copy an entity is, in general, quite complex, owing to the fact that, besides attributes, you also need to deal with the entity's relationships and copy them. I can not post here a huge amount of source code showing how to accomplish this, however, I can point you to a book where this issue is described in detail, with all of the source code you need. The book is the one from Marcus Zarra, "Core Data Appleā€™s API for Persisting Data on Mac OS X" by "The Pragmatic Programmers".
You really don't want to copy an Exam in this situation. You'd end up with lots of identically named Exams which didn't have a relationship with each other, and then you'd be forced to group them together (if you wanted to) by their name.
I'd recommend a new entity (perhaps "ExamSitting"?) which represents a Student sitting an Exam. You could then a to-many from Student to ExamSitting, and a to-many from Exam to ExamSitting. This enables you to have as many attributes on the ExamSitting as you like then (hasTaken, grade and so on).
Edit
Okay, given your clarification, I have a point or two to add (although they may not be what you're looking for). I understand that you're loading from files with a particular structure, but that doesn't necessarily have to dictate your structure.
With the XML files laid out as you now describe, I would still use an Exam - Student - ExamSitting model. If I were to implement it, I'd load all the Students, and then, for each record in the Exams file, I'd create one Exam object, and then a number of ExamSitting objects, one for each Student that fits the criteria defined in the record. As I mention above, this enables you to store more information about each event, such as mark, takenDate and so on.
If you're sure there's no requirement to be able to store additional information at this granularity, you could just create a to-many relationship studentsTakingExam. This could be populated as you load each exam record by querying the loaded Student entities.