tags:

views:

144

answers:

3

Hi all.

Wondering if my approach is ok or could be improved:

Public Class Company  
  private _id as Integer
  private _name as String
  private _location as String

  Public Function LoadMultipleByLocation(Byval searchStr as String) as List(Of Company)
     'sql etc here to build the list
  End Function
End Classs

Thoughts on having the object mapping like this?

+1  A: 

In this case, you would create an instance of Company, and then use it to return a List of Companies?

Some people do this, but I prefer to seperate my data object into a dumb data container:

public class Company : EntityBase
{
     private int _id;
     private string _name;
     private string _location;
}

I use a base class (EntityBase) that contains common methods for converting the dumb entity back into a collection of SQLParameters (for persisting), as well as instantiating it from a passed in SQLReader (this gets overridden in each concrete class, to map the reader to the private variables).

I then prefer to use a "Service" class that actually makes the database calls, creates the appropriate entity object, and returns it, I can utilize polymorphism here to reduce code duplication heavily.

FlySwat
A: 

Yes I would create an instance to get a list.

Using the EntityBase idea how would that work for different classes?

e.g Company, Orders, People.

Thanks for the reply.

A: 

@Dan

EntityBase would be a base class that each entity object would inherit, something like:

public class EntityBase
{
     public virtual string SaveSproc { get; }

     public virtual void LoadFromReader(SqlReader reader)
     {
     }

     public virtual void Save()
     {
         List<SqlParameters> paramList = = this.CreateParamsList();
         DoSqlStuff(this.SaveSproc, paramList);
     }

     public virtual List<SqlParamenter> CreateParamsList()
     { 
          return new List<SqlParameter>
     }
}

public Company : EntityBase
{

    private string _data;

public override string SaveSproc { get { return "SprocThatSaves"; } }

    public override List<SqlParameter> CreateParamList()
{ 
 List<SqlParameter> param = new List<SqlParameter>
 param.Add(new SqlParameter("Data",_data);

 return param; 
}

public override void LoadFromReader(SqlReader reader)
{
 // PsuedoCode
 _data = reader["data"];
}
}

Now, your DB tier can get a reader with company data, and do something like:

Company = new Company();
Company.LoadFromReader(reader);

And elsewhere, to save your data back:

Company.Save();
FlySwat