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 銷售模型加入你的專案,並設定專案使用實體框架。 為此,請完成 如何:手動配置實體框架 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 方法可在同一物件實例上多次呼叫。