How to use normal sql in ASP.NET MVC without EF?

2019-04-13 06:37发布

问题:

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);
}

回答1:

This is just a sample.(Tested & working ).That is y i am keeping the GetUniversities method inside the controller class . I suggest you to move the GetUniversities method to some service layer so that many UI/Controllers can use that.

    public ActionResult Index()
    {
       var items= GetUniversities();
       return View(items);
    }

    private List<DataRow> GetUniversities()
    {
        List<DataRow> list=null;
        string srtQry = "SELECT  U.* FROM Office O  INNER JOIN  
                         CampusUniversity CU ON  O.IdCampus equals CU.IdCampus
                         INNER JOIN UNIVERSITY U ON U.IdUniversity=CU.IdUniversity";
        string connString = "Database=yourDB;Server=yourServer;UID=user;PWD=password;";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            string strQry = "";
            using(SqlCommand objCommand = new SqlCommand(srtQry, conn))
            {
               objCommand.CommandType = CommandType.Text;
               DataTable dt = new DataTable();
               SqlDataAdapter adp = new SqlDataAdapter(objCommand);
               conn.Open();
               adp.Fill(dt);
               if (dt != null)
               {
                  list = dt.AsEnumerable().ToList();
               }
            }
        }
        return list;
    }

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

public ActionResult Index()
{
   var items= GetCustomers();    

   var newItems = (from p in items
                       select new
                       {
                           Name= p.Field<String>("Name"),
                           CampusName= p.Field<String>("CampusName")
                       }).ToList();

    return View(newItems);
}

This will give you a list of anonymous type which has 2 properties, Name and CampusName. 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.

public class UniversityViewModel
{
  public string UniversityName { set;get;}
  public string CampusName { set;get;}
}

Now we will update the code in our Index action like this.

var newItems = (from p in items
                 select new UserViewModel
                 {
                    UniversityName = p.Field<String>("Name"),
                    CampusName = p.Field<String>("CampusName")
                 }).ToList();

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.

@model IEnumerable<SO_MVC.Models.UserViewModel>
@foreach (var item in Model)
{
   <p>@item .UniversityName @item.CampusName</p>
}

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.



回答2:

This is not necessarily MVC specific. You could do the same thing in Webforms or Windows Forms, etc. Take a look at using ADO.NET for your queries or Dapper.



回答3:

SELECT
    u.*
FROM
    OFFICE c
    INNER JOIN CAMPUS_UNIVERSITY s ON c.IdCampus = s.IdCampus
    INNER JOIN UNIVERSITY u ON s.IdUniversity = u.IdUniversity