powlette
powlette

Reputation: 1800

Linq2Sql custom mapping

My question is: is there a way with a DataContext/Table mapping to implement some custom mapping code between the database and the creation of my entity instance?

For a simple example, say that my Products entity class has property "double Length {get; set; }"

and my entity and all my existing code is expecting Length to be in Feet, but in the database Length is stored in meters so I need to do a conversion. Is there a way to register a callback or otherwise insert some code to set object.Length manually based on a DataRow or however the data is retrieved internally by L2S ?

Yes, I thought I could set "double LengthInMeters { set { Length=value*0.3048; } }" but I was hoping to avoid making duplicate properties and introducing ambiguity about which to use. What I'd like to do is register a closure with my DataContext to be called after a Product is created so that I can say:

DataContext.Entity<Product>().OnCreated( (p, row) => 
{ 
  p.Length = row["Length"] * 0.3048; 
  p.ProductCode = row["Sku"].ToString().Substring(1, 5);
 ...etc..
});

Upvotes: 1

Views: 129

Answers (2)

Ryan Bennett
Ryan Bennett

Reputation: 3432

You can do it in the post creation. the .designer.cs class contains the OnCreated() Extensibility Method for your models. You can put it there. I would not do this however. It hides important logic. Place this code in your repository or some similar abstraction. I personally would probably get the model, then transfer the data to an application specific model before returning it from the repository. Then I'd convert it back when returning it to the repository. Not very speedy, but business apps dont usually require millisecond speeds where I work... maintainability is paramount instead.

Upvotes: 1

Randolpho
Randolpho

Reputation: 56391

Rather than do a post-creation event, I would suggest you simply do the conversion when you instantiate your entity. For example:

var qry = from product in dc.Products
          where product == something
          select new Product()
          {
              Length = product.Length * 0.3048,
              // etc.
          };
var normalizedProduct = qry.ToList();

Upvotes: 1

Related Questions