Recommended asp.net MVC model design approach

asp.net c# dapper orm

Question

I'm trying to decide the best approach for a new project I'm about to start on, when it comes to my model design (and I'm using Dapper.net).

I like the idea of having my models with objects rather than Foreign Key properties, i.e.

public Post LastPost { get; set; }

vs

public int LastPostId { get; set; }

However, if I implement this sort of nice clean approach, I have to multi-map to all objects (which leads onto potential circular referencing of objects within objects, (or have to stop multi-mapping at a certain point and therefore end up with NULL objects at some point down the object tree). Also, if I do multi-map to an extent, then Im perhaps causing unnecessary work, performing joins etc when they're not always going to be needed.

Or, if I decide to use multi-mapping to populate my objects within objects on a 'as needed' basis (in some of my repos methods perform multi mapping because its needed, and in other repos methods, don't bother populating the objects), then it feels kind of dirty in that I can't always be sure if an object (within an object) is null or not.

I've used NHibernate (or at least some of its more basic functionality) in the past and not had the dilemma as I always had objects within my models and if/when they were needed, I could rely on lazy loading to go get them - However, not having that lazy loading with Dapper.net I'm really unsure of the best approach to go with?

Accepted Answer

Why not have the best of both worlds?

bool _lastPostLoaded;
private Post _lastPost; 
public Post LastPost 
{ 
   get 
   {
      if(!_lastPostLoaded)
      {
         _lastPost = cnn.Query<Post>("select * from Posts where Id = @lastPostId", 
              new {lastPostId});
         _lastPostLoaded = true;
      }
      return _lastPost;
   } 
   set 
   {
      _lastPost = value;
      _lastPostLoaded = true;
   }
}

This allows you to eager load when needed with multi mapping and lazy load, when you are lazy;


Popular Answer

good, It is Lazy loading proxy pattern.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why