Soham Dasgupta
Soham Dasgupta

Reputation: 5199

Creating custom model using other models in ASP.NET MVC

As the title suggests I have two models Products And Orders which are actually two table in my database and I have used a LINQ to SQL class to create there models. Now I wan to create a model named "OrderDetails" which will have properties from both the model like product name and id from product and Order number from orders something like this. An then I want to create a view from this custom model and from which I want to add "CRUD" operation. What should be my approach. And in many scenarios I may have to use data from more than 4 models. Please help. I'm wondering helplessly and I have only two days experience in ASP.NET MVC.

Upvotes: 2

Views: 178

Answers (2)

joshperry
joshperry

Reputation: 42227

Linq to SQL does not support custom mapping to the extent that you're looking to do. What you'll want to look at is a full ORM. I highly recommend nHibernate, but Entity Framework, if you must, will do what you want.

Upvotes: 1

kevingessner
kevingessner

Reputation: 18985

I'd go this route:

namespace Models
{
    public class OrderDetails
    {
        private Products _products;
        private Order _order;

        public OrderDetails(Order order, Products products)
        {
            _order = order;
            _products = products;
        }

        // now expose whatever fields or logic you need.
        // for instance:

        public Customer OrderCustomer()
        {
            return order.Customer();
        }
    }
}

However, before you go around making all of these new models, are you sure you need them? Can you simply use two instances, either passed around separately or in a Tuple? You can get some useful abstraction here, but if you don't need it, keep it simple.

Upvotes: 1

Related Questions