Here is the code, then I will explain :)
public class Persona { public Persona() {
Your code for them to work together:
public void AgregaPersona(_Persona persona) { Persona per = new Persona() { Nombres = persona.nombres, ApellidoP = persona.apellidoP, ApellidoM = persona.apellidoM, FechaNacimiento = persona.fechaNacimiento, Sexo = persona.sexo.ToString(), EdoCivil = persona.edoCivil, RFC = persona.RFC, CURP = persona.CURP, Domicilio = persona.domicilio, CP = persona.codigoPostal, Telefonos = persona.telefonos, Celular = persona.celular, Email = persona.email, IDDel = persona.idDelegacion, IDEmpresa = persona.idEmpresa }; Referencia newRef = new Referencia { Nombre = referenciaNombre;
This is all you need to do to create two separate objects (as you expected) that are related to each other. Here is my best description of what is going on here.
When you create an ICollection<Referencia> Referencias , all this does is create a link (relationship) between the two objects ( Persona and Referencia ). Objects are still separate, only linked through this collection.
When you go to create Persona mappings with Referencia , you need to create your Persona , then you will create a separate Referencia object and related to it Persona , adding it to Persona display ICollection ( Referencias ). When the actual code is run to save this in the database, it will treat it as separate inserts, something like this pseudocode:
BEGIN TRANSACTION INSERT PERSONA GET PERSONA ID INSERT REFERENCIA USING NEW PERSONA ID(Repeat until all Referencias are inserted) COMMIT TRANSACTION
Now keep in mind the note I made about lazy loading. By default, whenever you download Persona , it does not load Referencias until you need it. It will only load these objects from the database if you try to access the values โโin this property. Thus, further emphasizing that these are indeed two separate objects.
In addition, you can create two-way matching if you want. You simply add one more link (relation), this time from Referencia to the corresponding Persona .
public class Referencia { public Int ReferenciaId {get; set;} public String Nombre {get; set;}
Note that the name of the property is the same as the class name. This is a convention, and if you deviate by calling the property something else, you need to add an attribute above your Referencias object in Persona . It is so that EF knows that this is a two-way communication. So, if you decided to name the Persona property in Referencia something like PersonaRef , then your code would look like this:
public class Persona { public Persona() {
Hopefully this will give you a better idea of โโhow relationships work in EF (and it translates pretty well with other ORMs). This way you get two different models that you need, and you can intersect them using relationship matching properties.
Here is a very good article about EF Code First by Scott Gu that you can find useful