views:

187

answers:

1

i was looking at an example of how to do an insert in Linq to SQL and here it was it said:

NorthwindDataContext context = new NorthwindDataContext();
context.Products.Add(new Product(..));
context.SubmitChanges();

but when i look at the below, (in my case the Table is UserInfo), the Table doesn't have an "Add" method:

public System.Data.Linq.Table<UserInfo> UserInfos
 {
  get
  {
   return this.GetTable<UserInfo>();
  }
 }

any clue what i am doing wrong here?

+2  A: 

You should use the InsertOnSubmit method:

NorthwindDataContext context = new NorthwindDataContext();
context.Products.InsertOnSubmit(new Product(..));
context.SubmitChanges();

The Add method exist on the EntitySet members, is mostly used when adding Child entities to a Parent one, for example:

var category = new Category{ Name = "Breveages"};


category.Products.Add(new Product{ Name = "Orange Juice"});
category.Products.Add(new Product{ Name = "Tomato Juice"});
category.Products.Add(new Product{ Name = "Cola"});

//...

context.Categories.InsertOnSubmit(category);
                                         // This will insert the Category and
                                         // the three Products we associated to.


EDIT: To do update operations, you just need to retrieve the entity by doing a query, or attaching it, for example:

var customer =  context.Customers.Single( c => c.CustomerID == "ALFKI");

customer.ContactName = "New Contact Name";
context.SubmitChanges();

The DataContext tracks the changes of its related entities and when the SubmitChanges method is called, it will detect that change, and generate an Update SQL statement behind the scenes to do the update operation...

CMS
thanks . . this works but now i realized that i dont want to add a new one but rather update an existing one . .what is the method for updating an existing record.
ooo
Product product = context.Products.Single(p => p.ProductID == 1);product.ProductName = "Kindle";product.UnitPrice = 359.99m;context.SubmitChanges();
Jason
One thing that you need to be careful about is the DataContext object. When you are updating be sure to get the object first from the database and then update it using a single DataContext object. If you try to attach an object of one DataContext to another DataContext then all hell breaks loose.
azamsharp