0

To best describe what I want to happen, i'll show what i'm doing, as to me it makes sense that this would work ...

public class foo()
{
    public foo()
    {
        MyContext db = new MyContext();
        foobar = db.foobar.first();
        this = Mapper.Map<bar, foo>(foobar);
    }
}

Basically, I want to use automapper within the destination class to map from the source class within the destination classes constructor.

Is there a way to do this?

Chris Missal
  • 5,516
  • 2
  • 25
  • 45
Riddick
  • 1,198
  • 4
  • 14
  • 23

1 Answers1

1

You cannot do this because this is read only in C#. You cannot assign this a value in the constructor. Not cool to try to change the reference of an object in its constructor. You will have to do the mapping manually and assign each individual property. I would also question if it as a good practice to assign an object values from a database or service in a default constructor. It is not very transparent to the user of the object what is going on and you can get an exception in your constructor.

Kevin Junghans
  • 17,102
  • 4
  • 42
  • 60
  • The plan was to use a base viewmodel that others would inherit, in order to pass data to the page master template. Is there a better way of doing this? – Riddick Dec 12 '12 at 10:44
  • 1
    The other reason I should have mentioned for not putting database mechanisms in your constructor is it strongly couples your persistence method with your entities or POCO's which will make your system fragile and inflexible. I would look at the Repository [http://msdn.microsoft.com/en-us/library/ff649690.aspx] pattern to decouple it even more. And to decouple it from object creation you may want to look at the Factory [http://msdn.microsoft.com/en-us/library/ee817667.aspx] design pattern. I will need more specifics on what you mean by "pass data to the page master" to provide more guidance. – Kevin Junghans Dec 12 '12 at 13:56
  • Hey, thanks i'll take a look at those. Basically I have a master template (editing the default _Layout.cshtml). With my new template I am gathering certain information, such as meta data and website title etc, from the database. I then want to use a viewmodel within _layout.cshtml to output this information, without it effecting the models passed to other Views. – Riddick Dec 12 '12 at 14:39
  • 1
    It is rarely recommended to use a model for _Layout but if you do a recommended approach is to have a base class, as you suggested and as discussed in this Q&A [http://stackoverflow.com/questions/4154407/asp-net-mvc-razor-pass-model-to-layout]. But that is a totally separate concern from initializing the model in the constructor with information directly from a database. You can still have a base ViewModel and use the decoupled methods I suggested to create it. – Kevin Junghans Dec 12 '12 at 15:25