I have this class using linq to sql, how do I implement the same by using normal sql in ASP.NET MVC 3 without use EF?
public ActionResult Index()
{
var List = (from c in db.OFFICE
join s in db.CAMPUS_UNIVERSITY on c.IdCampus equals s.IdCampus
join u in db.UNIVERSITY on s.IdUniversity equals u.IdUniversity
select u).ToList();
return View(List);
}
This is just a sample.(Tested & working ).That is y i am keeping the
GetUniversitiesmethod inside the controller class . I suggest you to move theGetUniversitiesmethod to some service layer so that many UI/Controllers can use that.Keep in mind that the GetCustomers method returns a List of DataRows. Not your custom domain entities. Entity framework is giving you the list of Domain Entities. So in the custom SQL case, you need to map the Data Row to an instance of your custom object yourself.
With LINQ, You can convert the List of DataRow to your custom objects like this
This will give you a list of anonymous type which has 2 properties,
NameandCampusName. Assuming Name and CampusName are 2 columns present in the result of your query.EDIT2 : As per the Comment, To List these data in a view, Create a view called Index inside your controller( where we wrote this action methods) folder under Views Folder.We need to make it a strongly typed view. But Wait! What type are we going to pass to the view ?
Our result is annonymous type. So We will create a ViewModel in this case and instead of annonymous, We will return a List of the ViewModel.
Now we will update the code in our Index action like this.
The only change is we now mentioned a type here. So the output is no more annonymous type. But known type.
Let us go back to our View and write code like this.
This view is strongly typed to a collection of our ViewModel. As usual we are looping thru that and displaying. This should work fine. It is Tested.