EntityCollection<TEntity>.Add(TEntity) Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Agrega un objeto a la colección.
public:
virtual void Add(TEntity entity);
public void Add(TEntity entity);
override this.Add : 'Entity -> unit
Public Sub Add (entity As TEntity)
Parámetros
- entity
- TEntity
Objeto que se va a agregar a la colección.
entity debe implementar IEntityWithRelationships.
Implementaciones
Excepciones
entity es null.
Ejemplos
Este ejemplo se basa en el modelo Adventure Works Sales. Para ejecutar el código de este ejemplo, debe haber agregado ya el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para que use Entity Framework. Para ello, complete los procedimientos descritos en How to: Manually Configure an Entity Framework Project (Cómo: Configurar manualmente un proyecto de Entity Framework ) y How to: Manually Define the Model and Mapping Files (Cómo: Definir manualmente los archivos de modelo y asignación).
En este ejemplo se crean dos nuevas entidades SalesOrderHeader, se agregan a la entidad Contact y, después de quitar un objeto, se usa el método Add para volver a agregar el objeto a la colección.
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
Contact contact = new Contact();
// Create a new SalesOrderHeader.
SalesOrderHeader newSalesOrder1 = new SalesOrderHeader();
// Add SalesOrderHeader to the Contact.
contact.SalesOrderHeaders.Add(newSalesOrder1);
// Create another SalesOrderHeader.
SalesOrderHeader newSalesOrder2 = new SalesOrderHeader();
// Add SalesOrderHeader to the Contact.
contact.SalesOrderHeaders.Add(newSalesOrder2);
// Get all related ends
IEnumerable<IRelatedEnd> relEnds =
((IEntityWithRelationships)contact)
.RelationshipManager.GetAllRelatedEnds();
foreach (IRelatedEnd relEnd in relEnds)
{
// Get Entity Collection from related end
EntityCollection<SalesOrderHeader> entityCollection =
(EntityCollection<SalesOrderHeader>)relEnd;
Console.WriteLine("EntityCollection count: {0}",
entityCollection.Count);
// Remove the first entity object.
entityCollection.Remove(newSalesOrder1);
bool contains = entityCollection.Contains(newSalesOrder1);
// Write the number of items after one entity has been removed
Console.WriteLine("EntityCollection count after one entity has been removed: {0}",
entityCollection.Count);
if (!contains)
Console.WriteLine("The removed entity is not in in the collection any more.");
//Use IRelatedEnd to add the entity back.
relEnd.Add(newSalesOrder1);
Console.WriteLine("EntityCollection count after an entity has been added again: {0}",
entityCollection.Count);
}
}
Comentarios
El método Add agrega un objeto a una EntityCollection<TEntity> y crea una relación entre los dos objetos. Cuando se asocia el objeto de origen a una instancia de ObjectContext, el método Add también agrega el objeto al ObjectContext. Esta operación se convierte en una operación de inserción en el origen de datos cuando se llama a SaveChanges. Para obtener más información, vea Crear, agregar, modificar y eliminar objetos.
Se puede llamar al método Add varias veces en la misma instancia de objeto.