ObjectContext.AddObject(String, Object) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将对象添加到对象上下文。
public:
void AddObject(System::String ^ entitySetName, System::Object ^ entity);
public void AddObject(string entitySetName, object entity);
member this.AddObject : string * obj -> unit
Public Sub AddObject (entitySetName As String, entity As Object)
参数
- entitySetName
- String
表示实体集名称,该名称可以选择由实体容器名称限定。
例外
示例
本示例添加新产品,并将更改保存到数据库。
Product newProduct;
// Define values for the new product.
string dateTimeString = "1998-06-01 00:00:00.000";
string productName = "Flat Washer 10";
string productNumber = "FW-5600";
Int16 safetyStockLevel = 1000;
Int16 reorderPoint = 750;
// Convert the date time string into a DateTime instance.
DateTime sellStartDate;
if (!DateTime.TryParse(dateTimeString, out sellStartDate))
{
throw new ArgumentException(string.Format("The string '{0}'cannot "
+ "be converted to DateTime.", dateTimeString));
}
// Create a new Product.
newProduct = Product.CreateProduct(0,
productName, productNumber, false, false, safetyStockLevel, reorderPoint,
0, 0, 0, DateTime.Today, Guid.NewGuid(), DateTime.Today);
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
try
{
// Add the new object to the context.
context.Products.AddObject(newProduct);
// Persist the new produc to the data source.
context.SaveChanges();
// Return the identity of the new product.
return newProduct.ProductID;
}
catch (UpdateException ex)
{
throw new InvalidOperationException(string.Format(
"The object could not be added. Make sure that a "
+ "product with a product number '{0}' does not aleady exist.\n",
newProduct.ProductNumber), ex);
}
}
注解
ObjectContext调用AddObject以将对象添加到对象上下文。 当对象是数据源中尚不存在的新对象时执行此操作。
对象将添加到处于ObjectStateManagerDetachedDeleted或Added状态。
在对象上下文中创建与另一个对象相关的新对象时,请使用下列方法之一添加对象:
对 Add 该方法 EntityCollection<TEntity> 调用并指定相关对象。 针对一对多或多对多关系执行此操作。
将 Value 对象的属性 EntityReference<TEntity> 设置为相关对象。 针对一对一或多对一关系执行此操作。
如果对象处于分离状态,则它不得具有 EntityKey。
格式的规则 entitySetName 如下所示:
DefaultContainerName如果该属性是
null,则必须entitySetName在实体容器名称<中>完全限定。<实体集名称>。如果没有DefaultContainerName,
entitySetName则可以是任一<实体容器名称>null。<实体集名称>或<实体集名称>。
object如果具有且EntityKeyentitySetName具有值,则EntitySet实体键必须与基于实体容器名称找到的entitySetName实体键匹配EntitySet。