Assume the following entity classes:
public class Player { public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual Team Team { get; set; } } public class Team { public virtual int ID { get; set; } public virtual string City { get; set; } public virtual string Nickname { get; set; } }
Assume the following display class for the Player class:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"> <class name="Player"> <id name="ID" column="ID" type="System.Int32" unsaved-value="null"> <generator class="native"/> </id> <property name="Name" column="Name" not-null="true" type="System.String" length="50" insert="true" update="true"/> <many-to-one name="Team" not-null="true" outer-join="auto" insert="true" update="true"> <column name="TeamID"/> </many-to-one> </class> </hibernate-mapping>
And suppose the following Player repository method:
public void Add(Player player) { using (ISession session = NHibernateHelper.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Save(player); transaction.Commit(); } } }
My question is:
Do I have to load a full-fledged command (parent) when I want to create a new player?
Or can I specify a mock object and specify only a foreign key?
Player player = new Player { Name = "Tom Brady", Team = new TeamRepository().GetTeamByCityAndNickname("New England", "Patriots") // Is this the only way? // or can I do this? // Team = new Team { ID = 22 } }; new PlayerRepository().Add(player);
- And if I can not specify the "layout" of the object (by specifying only the foreign key), can you explain why I can not?
- That is, could you give me an idea of ββwhat is happening under the hood?
Heads-Up:
- Interestingly, while talking about EF 4.0 during the DotNetRocks episode , Julia Lerman admitted that many people want to use a foreign key in these types of situations.
EDIT: This answer points to the essence of my question.
Think of it as having an object that only stores Id and loads the rest if you ever need to. If you just pass it on to create relationships (like FK), id is all you ever need.
- Well, if that is the case, then why do I need to worry about proxy objects, etc.? Why can't I just create a "dummy" object and specify the value of the foreign key, if this is really important?
source share