0

I'm bullding a project that takes data from sql and other data sources and stores in mongo db.

I have classes that map to the documents, for example:

public class Event
{
    public virtual int Id { get; set; }
    public virtual int Name { get; set; }
    public virtual int Description { get; set; }
    public virtual IEnumerable<string> Attendees { get; set; }
}

Note - properties marked virtual as these classes are used for nhibernate mappings also (in some cases)

Then, we have a separate user class / collection:

public class User
{
    public virtual int Id { get; set; }
    public virtual int FirstName { get; set; }
    public virtual int LastName { get; set; }
}

In my app, I have, for example, an EventController, that returns a list of events. I also want “real” hydrated Users back with my event.

So, currently, I have the above 2 classes - Event and User, in a different project / namespace. In this case, they’re in MyApp.DTOs

I then have another Namespace called MyApp.Model

Which has near duplicate classes

public class Event
{
    public virtual int Id { get; set; }
    public virtual int Name { get; set; }
    public virtual int Description { get; set; }
    public virtual IEnumerable<User> Attendees { get; set; }
}

public class User
{
    public virtual int Id { get; set; }
    public virtual int FirstName { get; set; }
    public virtual int LastName { get; set; }
}

Then, to keep my controllers skinny, I have an event service that returns Model.Event, and encapsulates the repository / db logic in there:

Get the event documents (DTOs.Event) Get the user documents (DTOs.User) Use automapper to create Model.User

I’m just wondering if there’s a better way, as this results in a lot of duplicate code!

4

1 に答える 1

2

Unfortunately in order to have your models distinct from your domain you need to have some code duplication especially when most of the times your DTOs match your models.

Its mostly a preference but I believe models should be exposed to your views and have nothing do to with the domains or mapped nh objects.

于 2012-08-20T21:49:25.633 に答える