EntityCollection<TEntity>.Add(TEntity) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将对象添加到集合。
public:
virtual void Add(TEntity entity);
public void Add(TEntity entity);
override this.Add : 'Entity -> unit
Public Sub Add (entity As TEntity)
参数
- entity
- TEntity
要添加到集合的对象。
entity 必须实现 IEntityWithRelationships。
实现
例外
entity 是 null。
示例
此示例基于 Adventure Works 销售模型。 若要运行此示例中的代码,必须将 AdventureWorks 销售模型添加到项目中,并将项目配置为使用 Entity Framework。 为此,请完成 如何:手动配置 Entity Framework Project 和 如何:手动定义模型和映射文件。
此示例创建两个新 SalesOrderHeader 实体,将其添加到 Contact 实体,在删除对象后,使用 Add 该方法将对象添加回集合。
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);
}
}
注解
该方法 Add 将对象添加到两 EntityCollection<TEntity> 个对象之间并创建关系。 当源对象附加到ObjectContext实例时,Add该方法还会将对象添加到 .ObjectContext 调用时 SaveChanges ,此操作将转换为数据源中的插入操作。 有关详细信息,请参阅 创建、添加、修改和删除对象。
Add可以在同一对象实例上多次调用该方法。