Geeks With Blogs
Create Fun Things - Samer's Developer Blog Development Blog for C#, .NET and Obj-C

So when I first started working with SQL Server 2008 and LINQ, I would pretty much just use the LinqDataSource because it was definitely the easiest to use. It’s pretty good for testing purposes, or really small projects, but if you’re doing anything that is going to grow / is large already, then you’ll probably not want all that logic embedded in your pages.

As I became more comfortable with LINQ, I decided to take on the task of switching over to the ObjectDataSource to bind to my ListViews. Here’s a quick and easy process to get started doing that.

Step 0: Assumptions I’m going to make about what you’ve done so far

I’m assuming that you already have some sort of working database, and that you’ve created a DataContext (i.e. a LINQ to SQL file, or .dbml). (You know, dragging and dropping those tables, which just takes so much work.)

If you didn’t know what all was going on in the background, then I don’t blame you. The short version of it is that it’s generating a bunch of classes to match the tables in the database. It’s pretty awesome if you ever get into the details, but for the purposes of this tutorial, we’ll just stick to that.

For this example, we will be working with a made up class/table called “Person”.

Step 1: Add a class file to the project

I name the file Person.cs and get started.

We’ll want to add some things to make this easier to hook up to an ObjectDataSource. Add in “using System.ComponentModel” up top. That allows us to mark the class as a DataObject, which just organizes it better and makes the data source wizard easier to work with. We can go ahead and mark it above the class declaration as [DataObject(true)].

We need to do some other things. Since there is already going to be a Person class/object (that was created by the DataContext), we need to mark it as a partial class. Partial classes are great, because it lets you split up methods / properties across multiple class files that all get compiled into 1 class.

Up to this point, the file should look something like this:

image

 

Step 2: Create the basic 4 methods that you will likely use in a DataSource (Select, Update, Delete, Insert)

We’ll want to create some custom methods that we can hook up our data source to in order to do those actions in the database. I’m going to write up the method declarations, without any of the logic inside yet. Feel free to name your methods anything you’d like, but I’d recommend sticking to something that resembles the action they are doing.

public static IEnumerable<Person> SelectAllPeople()
    {

    }

    public static void UpdatePerson(Person myPersonToUpdate)
    {

    }

    public static int CreatePerson(Person myPersonToCreate)
    {

    }

    public static void DeletePerson(Person myPersonToDelete)
    {

    }

 

Using the ComponentModel namespace, I’m going to mark each of these with some attributes that will help the wizard identify each method’s action automatically. It will then look like this:

[DataObjectMethod(DataObjectMethodType.Select,true)]
public static IEnumerable<Person> SelectAllPeople()
{

}

[DataObjectMethod(DataObjectMethodType.Update,true)]
public static void UpdatePerson(Person myPersonToUpdate)
{

}

[DataObjectMethod(DataObjectMethodType.Insert,true)]
public static int CreatePerson(Person myPersonToCreate)
{

}

[DataObjectMethod(DataObjectMethodType.Delete,true)]
public static void DeletePerson(Person myPersonToDelete)
{

}

The “true” part is optional, and it tells the program that this is the default method for that particular type. (i.e. all 4 of these are considered the default methods for Select, Insert, Delete and Update respectively.)

 

Step 3: Making these methods do something

So now that you have the basic structure of the class file, we want to actually write up the logic to make it do what it’s supposed to do!

The first method will be our select method. I’m going to create an instance of the datacontext, and then return all the persons in the database.

The second method is our update method. I need to create an instance of the datacontext, attach the type to it (since it’s being passed in “un-attached”), then submit the changes. Note: The attach method overload I use assumes that the database table has a timestamp column in it. I typically call mine “Version”.

The third method is our insert method. Again, create an instance of the datacontext, call its insert on submit and then submit the changes. We’ll return the primary key of it once it works.

Finally, the fourth method is our delete method. We’ll need to attach it to the datacontext (this time, not telling it that changes have been made) and then call DeleteOnSubmit. Submit the changes and it’s done.

It should look like this (Note: Your datacontext name will probably be different.)

image

 

Step 4: Hooking it up to an Object Data Source/ ListView

Ok, great! The “hard” part is over, so now to see the results. I’m going to open up my Default.aspx page and drop on a ListView and then use the little smart tab to hook it up to a data source. It should look something like this:

image

 

On the next wizard, you’ll want to select your data object. In my project, I’ve selected the “Person” object:

image

You’ll notice that I have [X] Show only data components checked. That’s where the [DataObject(true)] comes in. It will only show business objects that have that attribute. That way you don’t have to wade through tons of other class files (depending on your project.)

If you notice on the next screen, it already has all those 4 methods showing up in each of their proper tabs. For example, without me selecting anything, I see my default insert method is already selected for me.

image

Note: If you had extra methods for each of the 4 operations, you can simply select them from the drop down.

You can now click Finish and you’re good to go! You can then define the item templates any way you want in the ListView and do all that stuff that you’d normally do at this point.

In the aspx code, you’ll notice the ObjectDataSource looks something like this:

<asp:ObjectDataSource ID="PersonObjectDataSource" runat="server" 
     DataObjectTypeName="Person" DeleteMethod="DeletePerson" 
     InsertMethod="CreatePerson" OldValuesParameterFormatString="original_{0}" 
     SelectMethod="SelectAllPeople" TypeName="Person" UpdateMethod="UpdatePerson">
 </asp:ObjectDataSource>
 

Final Thoughts: What makes this better than my old way of doing things?

Ok, so that seemed like a lot of work and you get the same functionality in the end, right? Well, sort of. Here’s what I really like about doing all my data binding in this way:

  1. You can now add in tons of custom methods in the class file, and consume them as needed. For example, I can add in a new Select method that only selects people who are active and use it all over the program in the same way.
  2.     [DataObjectMethod(DataObjectMethodType.Select)]
        public static IEnumerable<Person> SelectActivePeople()
        {
            ManagementDataContext db = new ManagementDataContext();
            return db.Persons.Where(m => m.IsActive == true);
        }
     
  3. You now have a great separation between your data access layers / business objects and your user interface. If you were to keep using the LinqDataSource or some other data source that keeps its logic in the aspx page, then you’ve now hooked up your logic into your page. This kinda sucks, because if you had several pages that needed to select all the people, then you’d have to make sure you maintain all those pages individually. If you changed the logic on 1 page, you’d have to remember to change it in every other location. This can get really nasty as your program grows. With the method described in this article, you can now just maintain it in 1 place and it’ll update everything that calls that method!
  4. This method is very easy to expand upon, once you do the initial grunt work. Need to add more methods? No problem, type them up. Need to change the IsActive to ignore people who were created in the past month? No problem!

 

I could write more about all this, but i think this is a good start.. You can definitely get more complicated as time goes by but I’ll write about that later.

 

Cheers!

Posted on Sunday, July 26, 2009 10:24 PM Tutorials | Back to top


Comments on this post: Tutorial: Why the ObjectDataSource is my best friend

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
Excellent stuff. I did not know about this, it looks awesome...
Left by Liviu on Jul 27, 2009 6:52 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
Great and simple tutorial, thanks for sharing
Left by Mohammad on Aug 26, 2009 1:27 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
I love the tutorial but i'm having some trouble trying to get the ObjectDataSource to work when my Insert funtion passes in the business object. It seems like it's looking for each of the field names that are being bound in the control. It would be very helpful to see how you actually bind a formview (or some other control) and make the insert function actually work.

[DataObjectMethod(DataObjectMethodType.Insert, true)]
public static void InsertPerson(Person person) {
//do something
}

I'm just binding with : Text='<%# Bind("name") %>'
but when i execute the insert statement it's having trouble with the parameters not matching up. I would expect to have the person object in the ObjectDataSource_Inserting event but instead all the individual fields I databound.

What am I missing?
Left by Shaunt on Oct 22, 2009 7:54 PM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
Thanks a lot.. Tutorial was really helpfull.
Left by Nalaka526 on Jan 26, 2010 12:13 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
How do you use optimistic conccurency with the update and delete statement??
thnx
Left by JimJonez on May 04, 2010 2:40 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
Thanks for the tutorial. Really helps explain the benefits of ObjectDataSource.
Left by bytesync on Jun 05, 2010 10:14 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
Great ! Thanks.
The only problem I have is that the Delete method in Linq does not work. It does not pass the parameter (in your case, myPersonToDelete).
Is that a know Linq to SQL problem or so ?
Left by Johan on May 11, 2011 9:13 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
I was with you up until step 4. No idea how to "drop in a listview" or bring up that Choose Data Source window. Could you explain that a bit more.
I'm using M$ Visual Web Developer 2011 Express, will this work on that?
Left by David Newcomb on Jul 19, 2011 11:29 AM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
How to make the CRUD functions work, if the Person object has a property of collection type? Such as
Person()
{
... ...
List<Person> Children{get;set;}
}
Left by George on Oct 08, 2014 9:42 PM

# re: Tutorial: Why the ObjectDataSource is my best friend
Requesting Gravatar...
i am facing an issue with object data source. i am using parameterized select method and i am using a selecting method to select it and this selecting methos is reding from web pages controls but for multiuser cae controls are null because select method re-initialize page, i have tried making select method static but selecting method can not be static and when its reading contols values these are null.
Left by Anil Arora on May 05, 2016 4:48 AM

Your comment:
 (will show your gravatar)


Copyright © samerpaul | Powered by: GeeksWithBlogs.net