Inserting Sharepoint List Item using SPMetal Classes

Microsoft has introduced a very useful tool, in the form of SPMetal, for performing CRUD (Create Read Update Delete) operations on sharepoint lists. This article shows how to insert a new item into a list. The below screen shot has an example with its explanation as given below.

Insert item using SPMetal

Sample source code

If you have not yet generated the Data Context and entity classes, follow the below link and generate your entity model –

Using SPMetal With Paramenters

  1. Instantiate an object of the data Context class by passing the site Url as a parameter.
    • DemoDataContext demoDataContext = new DemoDataContext(spWeb.Url);
  2. Create a generic object of EntityList having the List Entity as its source.
    • EntityList<CitiesObject> cities = demoDataContext.GetList<CitiesObject>(“Cities”);
    • The EntityList class can be found in  Microsoft.Sharepoint.Linq namespace.
    • In this example I have taken a list named Cities which has three custom columns namely CityName, State and Country apart from the out-of-the-box columns.
    • The entity corresponding to Cities is CitiesObject, which is passed to the generic method.
    • The GetList method of the DataContext object returns a reference to the List to which we are adding an Item.
  3. Create and instantiate an object of List type which is passed as source to the EntityList class above.
    • CitiesObject city = new CitiesObject() { Title=”New City”, CityName=”Pune”,Country=”India”,State=”Maharashtra”};
    • In my case I have created an object of type CitiesObject and have assigned value to its properties.
  4. Add the list item to list.
    • cities.InsertOnSubmit(city);
    • The above method InsertOnSubmit adds the list item to list. But these changes remain in memory.
    • If we have a collection of List Items, we can add the whole collection at on go, using a Method called InsertAllOnSubmit(IEnumerable<T>)
  5. Persist the changes
    • demoDataContext.SubmitChanges();
    • The SubmitChanges method is where the changes made above are actually persisted in the content Database.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s