9

阅读这篇题为“使用 ObjectSet(实体框架)”的 MSDN 文章,它展示了两个关于如何添加产品的示例。一个用于 3.5,另一个用于 4.0。

http://msdn.microsoft.com/en-us/library/ee473442.aspx

由于我缺乏知识,我可能在这里完全遗漏了一些东西,但我从未添加过这样的产品:

   //In .NET Framework 3.5 SP1, use the following code: (ObjectQuery)
   using (AdventureWorksEntities context = new AdventureWorksEntities())
   {
      // Add the new object to the context.
      context.AddObject("Products", newProduct);
   } 

   //New in .NET Framework 4, use the following code: (ObjectSet)
   using (AdventureWorksEntities context = new AdventureWorksEntities())
   {
      // Add the new object to the context.
      context.Products.AddObject(newProduct);
   }

我不会这样做,只是使用:

   // (My familiar way)
   using (AdventureWorksEntities context = new AdventureWorksEntities())
   {
      // Add the new object to the context.
      context.AddToProducts(newProduct);
   }

这三种方式有什么区别?

“我的方式”只是另一种使用 ObjectQuery 的方式吗?

谢谢,科汉

4

1 回答 1

9

All of them do the same thing, with minor differences in syntax.

First, let's look at the 3.5 way and "your way." If you look at the codegen file for your EDMX, you'll see something like:

    public void AddToProducts(Product product)
    {
        base.AddObject("Products", product);
    }

So these two methods are exactly the same, except that the magic string in your code is replaced by a codegened version which can never be wrong.

The ".NET 4 way" does the same thing, but does it differently. It uses the strongly typed ObjectSet<T>, which allows you to create a strongly-typed reference dynamically but without using strings. In the case of adding an object to a context, though, there's not a real advantage that I know of, except that it allows you to be more consistent about how you reference your entities -- you read them from the context using the same property (Context.Products) which you use to write them.

于 2010-05-11T13:41:22.463 回答