Ryan
Ryan

Reputation: 4414

Dynamic view models with validation

So I have a database full of products that have attributes and those attributes have values. I need to be able to re-create this as a C# object that I can use as a view model.

So essentially I need to be able to turn what I have in the database into this:

public class Product
{
    public object Attribute { get; set; }
}

I'm guessing I will have to use reflection or expression trees for this, but I'm not sure. I also need to include validation on each attribute as well. I was thinking of using a framework called Clay to do this although I don't know if I'd be able to get the validation and/or be able to POST back this view model back to the controller.

Any ideas?

EDIT: Thanks for the answers everyone but I must have not made it clear what I was looking for my fault.. I was looking into using DynamicObject to create an object from the data that I have in a database. I'm just not to sure how to use DynamicObject to also create DataAnnotations at runtime.

Upvotes: 1

Views: 567

Answers (2)

jim tollan
jim tollan

Reputation: 22485

Ryan,

As per LiquidPony's comment, I'd pull Entity framework into the mix. There a re a variety of entry points to using EF, either Database first, Model-First or Code-First. For your purposes, Database first would be the best fit. Basically, you just point the edmx designer canvas at your db connection and then 'drag' the tables that you need onto the surface. This then creates the required entity classes which can be consumed witihn your service layer/controller using linq.

The beauty here is that all your foreign key relationshipsare properly represented and you can access child collections etc with relative ease.

Prior to EF, I did indeed use T4 templates and reflection to output my db mapping classes and altho it was a 'success', it was also a constant maintenance nightmare as I had to remember to add new properties if the db changes etc. With EF, you just press 'refresh' and this is all done for you. Now, had this been a greenfield project, you could go one step 'better' and use EF Code-First. This allows you to create your domain model manually and have the db generated around the requirements of the model. This has real advantages inside the realms of creating self contained components that are designed as part of a larger system.

See:

Code-first vs Model/Database-first

and:

http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx

for nice summaries of each approach.

Hope this gives some insights.

Upvotes: 1

M.Babcock
M.Babcock

Reputation: 18965

If you're using MVC3 then the typical way I've seen this done is using the Entity Framework and Unobtrusive Javascript/DataAnnotations for validation.

Validation tutorial

MVC3 + EF4 tutorial

Upvotes: 0

Related Questions