views:

40

answers:

1

Hi there,

I want to improve the program so it has a proper constructor but also works with the models environment of MVC.

I currently have:

public void recordDocument(int order_id, string filename, string physical_path, string slug, int bytes)
        {
            ArchiveDocument doc = new ArchiveDocument(); 
            doc.order_id = order_id; 
            doc.filename = filename; 
            doc.physical_path = physical_path; 
            doc.slug = slug; 
            doc.bytes = bytes; 
            db.ArchiveDocuments.InsertOnSubmit(doc); 
        }

This obviously should be a constructor and should change to the leaner:

  public void recordDocument(ArchiveDocument doc)
    {
        db.ArchiveDocuments.InsertOnSubmit(doc); 
    }

with a get & set somewhere else - not sure of the syntax - do I create a partial class?

so: creating in the somewhere repository -

 ArchiveDocument doc = 
        new ArchiveDocument(order_id, idTaggedFilename, physical_path, slug, bytes);

and then:

namespace ordering.Models
{

    public partial class ArchiveDocument 
    {
       int order_id, string filename, string physical_path, string slug, int bytes;


      public archiveDocument(int order_id, string filename, string physical_path, string slug, int bytes){
              this.order_id = order_id;
              etc

     }

}

How should I alter the code?

A: 

I would avoid using constructors for models

We use a constructorless model and auto properties, then we use the initializer to assign that way the DataBinder can create the model and we get maximum reuse, where we only assign the properties needed for the particular view

e.g.

public class AModel{

    public int Id{get;set;}

    public string Name{get;set;}

}

var aModel = new AModel{
    Id= dataSource.Id,
    Name = dataSource.Name
    };
Anthony Johnston
May I ask why you do not like to use constructors in models? I am sometimes using them when model intialization is complex and needs to be re-used and it works fine for me.
Adrian Grigore
we use models to transport data to the view, any complexity is done in the controller - so we don't need them.It also allows your models to be created by the ModelBinder, in the case of a model as a parameter in a controller action, the modelbinder can only do this if there is a public parameterless constructor available.We use constructors elsewhere to define a contract for creating an object - just not for models
Anthony Johnston