views:

178

answers:

4

I'm just getting my head round C#. I've been creating classes and objects so say i created a class called Member:

 public class Member
 {
     public int MemberID;
     public string FirstName;
     public string LastName;
     public string UserName;
 }

and I create a new object of that class by doing this:

    Member Billy = new Member();

    Billy.UserName = "Jonesy";
    Billy.FirstName = "Billy";
    Billy.LastName = "Jones";

That's all fine but what if I've queried a database and gotten back 5 members, can I create objects on the fly? Or what is the best way to store these members in memory?

I've used VB.Net where I would just add them into a datatable. But I've never really done any object-oriented programming before and thought since I'm learning C#, now's the best time to learn OOP.

+1  A: 

This is a common problem. Fortunately there is a good answer to this: Linq To Sql! You can read about it here: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

What it basically does is that it creates a class, one per table you choose in your database. This makes it very easy to get all your objects directly from the database into object oriented programming.

Saving is as easy as calling a function "SubmitChanges()". There are more providers for this but I think Linq will suit you well as a beginner as it abstracts a lot of the annoying parts.

Oskar Kjellin
thanks I'll check out the post!
iamjonesy
+1  A: 

I'd recommend that you look at LINQ to SQL. Then you can write code like this to query the database to get a specific user:

Member member = db.Members.Single(member => member.UserName == "Jonesy");

or to get users matching a criterion:

IQueryable<Member> members = db.Members
    .Where(member => member.LastName == "Jones");

LINQ to SQL also takes care of writing the boilerplate code to declare the classes based on the database structure.

Mark Byers
cheers it seems like LINQ to SQL is the way to go!
iamjonesy
+1  A: 

If you don't go with LINQ to SQL (or the Entity Framework) then using a regular ADO.NET DataReader you would loop through the results, instantiate a new object with the details, and add it to a list.

Roughly it would look like this:

List<Member> members = new List<Member>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Member member = new Member();
                member.UserName = reader.GetString(0);
                member.FirstName = reader.GetString(1);
                member.LastName = reader.GetString(2);
                members.Add(member);
            }
        }
    }
}

foreach(Member member in members)
{
    // do something
}
Ahmad Mageed
thats kinda what I had in mind! In terms of best-practice is it better to take the time to learn LINQ to SQL or could I just stick to good old SQL?Cheers
iamjonesy
@Jonesy this was around before LINQ to SQL and it's the vanilla approach to database interaction (there are also typed DataSets) and is the closest to the metal but doesn't generate any classes for you. LINQ to SQL / EF are Object Relational Mappers (ORM) and generate classes for you. So it all depends on what you want to do. LINQ to SQL uses this stuff under the hood. Best practices don't dictate the technology to use, but rather how to use each technology. Meaning, there are best practices in ADO.NET, LINQ to SQL, etc.
Ahmad Mageed
Yeah I think i'd rather just define the classes myself and then create objects this way. Cheers!
iamjonesy
@Jonesy I posted with this info to demonstrate the most basic way to do things. Of course, if you have time, definitely play around with the other options. They do drastically cut down on development time but you need to learn how to use them. StackOverflow uses LINQ to SQL :) Entity Framework is the new technology Microsoft is pushing for.
Ahmad Mageed
@Ahmad: -1 for setting a bad example. The `SqlCommand` and `SqlDataReader` both need to be in `using` blocks. Correct that and I'll remove the downvote.
John Saunders
@John fixed, thanks.
Ahmad Mageed
@Ahmad: I removed the downvote.
John Saunders
A: 

Linq2Sql suggested twice is not the only way, but having in mind case when all objects can be one to one mapped to tables in your database it works just fine. Personally I would go for EF instead however, because it allows you to have one more layer of abstraction.

Also I can suggest you to look at db4o and etc, there you just can save you poco and that's all.

vittore
@vittore: I suggest you elaborate on what you mean by "one more layer of abstraction". _I_ know you mean the classes don't have to be one-to-one with the database, but the OP may now know. That's especialy true since he's been getting so many suggestions to use LINQ to SQL.
John Saunders
@John Saunders: thanks for advice, however the main point of my message was to look at db4o, as it could be very simple implementation of persistence in some cases.
vittore
@vittore: in that case, I suggest you start a new paragraph starting at "Also I can suggest".
John Saunders
@John Saunders: actually it was, but having one CR do not start new paragraph, don't now why, when i put enter twice - it works
vittore
@vittore: see http://stackoverflow.com/editing-help or the "How to format" box when you ask a question and click in the body.
John Saunders
thanks for this link
vittore