Doctrine optional OneToOne mapping - orm

I'm trying to create a optional OneToOne mapping in Doctrine.
I have a table with all cities and zip codes available (this table shouldn't be changed), and I have a table with addresses and a mapped city. But sometimes I don't want to add City to my Address at the beginning (maybe later on it will). But when I don't add a City to the Address the persist on the Address gives me a Reflection Exception because there is no object like 'null' , which should be de City object.
I don't want to add an empty city every time into the database, because there should nothing be added or deleted to the city table.
Any suggestions? Or what am I missing?
class Address{
/**
* #OneToOne(targetEntity="City")
* #JoinColumn(name="city_id", referencedColumnName="id")
*/
private $city = '';
Possible solutions I considered:
Create an empty city object in the db and assign this always to newly created Address objects (might cause a lot of overhead)
Create a ManyToMany relationship with an array of cities, so there can be zero or more cities added (I can restrict the multitude of cities in my Address object) but then I need a mapping table...

Just simply add nullable=true to #JoinColumn annotation

Related

Merge objects within Entity Framework?

I'm attempting to create a merge function, in my application i have a users object that has PK/FK relationship to other objects relating to that user. (for my example say Contact is the object, and Orders have a 1:Many relationship to Contacts.
The function would pass in two EF objects, with one being the "kept" record and the other being "merged". Whereby all data in the kept should win should there be duplicate field entry. This is all easy enough, but i can't understand how to point all the link objects to the new record PK/FK issue.
How can this be achieved within EF(Design first)?
Example code from MS - Can i simply load the objects related to the merge and change their FK relationship? (differentcontact in example below). Such that say a Contact was created twice, and orders exist under both Contacts, we want to keep the first Contact, and remove the duplicate one. First we must re-assign all the orders to the correct contact (differentcontact), and then would be able to remove the duplicate contact value?
Using context As New POCOAdventureWorksEntities()
Dim orderId As Integer = 43659
Dim differentContactID As Integer = 5
Dim order As Order = context.Orders.Include("Contact").Where(Function(o) o.SalesOrderID = orderId).First()
Dim differentContact As Contact = context.Contacts.First(Function(c) c.ContactID = differentContactID)
order.ContactID = differentContact.ContactID '// Something like this?
context.SaveChanges()

How to determine number of children of a record?

Good afternoon everyone!
I'm studying NHibernate, and decided to make some changes. Among them, I noticed that some fields are unnecessary. So I bring my doubt:
I have a list, let's call it Class_List within each study class, I can have N students for each class. Within the list Class_List, I also have other properties as simple as the name of the class.
How I see it is unnecessary to store how many students I have in the database, I would, in a single query, how many records I have. This, using NHibernate.
Is this possible? How?
Best regards,
Gustavo.
Edit: I've forgot to say one thing... I want to return this number of record, as a column. But this column is not mapped in my .hbm.xml file.
If students are mapped as a collection on Class, you can try using something like this:
var numberOfStudents = session.CreateCriteria<Class>()
.Add(Restrictions.IdEq(1))
.CreateCriteria("_students", "students")
.SetProjection(Projections.RowCount())
.UniqueResult<Int32>();
Where '1' is the id of the class (you can use other property) and '_students' is the name of the students collection.

NHibernate associate class without pulling from repository

I'm sure I've done this before but I can't recall how. I have 2 classes, say Person and Company. I'm instantiating a new Person and want to set it up so that when I save it to repository it will be associated with Company A. Company A already exists but I don't want to pull the entire thing from the DB just so I can write:
person.Company = CompanyA;
How can I set the Person's Company property so that it will be associated with CompanyA without pulling CompanyA from the DB? I definitely don't want to map the CompanyID property btw!
Use ISession.Load(id). Ayende has a good post about Get vs. Load.
person.Company = session.Load(companyAId);

Mapping lookup table to class

I have a reference/lookup table whose main purpose is to provide the user with a list of existing options. The user will also have the ability to enter new items into the list. How would you map this in NHibernate?
For example, say I have an Address class with a City field. The database has an Address table and a City lookup table. (I can define the relationships however I want at this point.) When editing the address:
The user can select any available City, or can enter a new City.
A new city entered must be added to the lookup table.
Editing an Address instance's city should either change the reference - if the edited city also exists in the DB - or create a new City entry by that name and refer to it. (If I edit "Chicago" to "New York", I don't want all addresses in Chicago to change to New York; just the one I'm looking at.)
I've been scouring NHib docs, and I'm not at all sure what approach I should take.
EDIT:
Part of my issue stems from the fact that I'm trying to avoid creating a "City" class with a single property - I'd just like Address.City to be a string in the domain model. This may be unwise, I don't know.
So you have addresses and you want a distinct list of cities. You'll either need to do the "distinct" operation in your code or in the database. Doing it in code implies a City class mapped onto your City table - I can't see how you can avoid it.
If the "distinct" operation is done it the database, you'll need write sprocs to insert and update an Address. These sprocs would then contain the logic of "use the City if it's in the table, otherwise create a new one".
Personally I'm not in favour of sprocs if they can be avoided and so I'd recommend that you create a City class and map it with a on your Address class.

DDD: Should 'country' be a Value Object or an Entity?

'country': Value Object or Entity in DDD?
Opinions either way appreciated.
And, where to store the table of country names/codes?
DB?
XML?
In a class?
Thanks!
If your domain is geographic or political, then it might be an entity, but in the average case, a country is just a value associated with things like addresses. In that case, in the context of your object model, it's just a value.
As for storage, the domain model doesn't really care. You can use the database if it's convenient, XML if you prefer, and a class if you have behavior associated with countries.
One of the characteristics of an entity is that it has a life cycle, i.e. it changes over time. A value object does not. In fact, value objects should be immutable. So the question to ask yourself is, "Does the country object change over time?"
Another aspect which differentiates entities and value objects is that two value objects with the same properties are the same. So if you have an instance of country with the name "France", it's the same as another instance of country with the name "France", even though they are two distinct instances (assuming that's the only property of country for the sake of this discussion). Think of strings in most languages, the string "fubar" equals another instance of the string "fubar".
Entities, on the other hand, are distinct even if they have the same properties. One customer with the name "John Smith" may not be the same as another customer with the name "John Smith".
So given these characteristics you should be able to decide. Since there can be only one "France" and it doesn't change over time, it's probably a value object - unless your app needs to track more about a country which may change over time.
Imagine:
You have another entity - Customer.
Customer entity references Country object.
You have 2 entity instances with filled Country objects with same value (i.e. "France")
You are deleting country object from first entity (or first entity object)
if you want country to be deleted for 2nd entity object too
=> Country is an entity object
if you vant country to be deleted only for 1st entity object
=> Country is a value object