如何使用SQL正常在ASP.NET MVC中没有EF? [英] How to use normal sql in ASP.NET MVC without EF?

查看:185
本文介绍了如何使用SQL正常在ASP.NET MVC中没有EF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用LINQ to SQL的这个班,我怎么在ASP.NET中使用普通的SQL MVC 3不使用EF实现相同的?

 公众的ActionResult指数()
{
    VAR名单=(从db.OFFICEÇ
                 加入S IN db.CAMPUS_UNIVERSITY上c.IdCampus等于s.IdCampus
                 走进你的db.UNIVERSITY上s.IdUniversity等于u.IdUniversity
                 选择U).ToList();    返回视图(列表);
}


解决方案

这仅仅是一个样品(测试和安培;工作)。那是易建联正在保持 GetUniversities 控制器类中的方法。我建议你​​移动 GetUniversities 法的一些服务层,使许多UI /控制器可以使用。

 公众的ActionResult指数()
    {
       变种项= GetUniversities();
       返回查看(项目);
    }    私人列表<&的DataRow GT; GetUniversities()
    {
        清单<&的DataRow GT;名单= NULL;
        字符串srtQry =SELECT * U.从办公室ØINNER JOIN
                         CampusUniversity CU ON O.IdCampus等于CU.IdCampus
                         INNER JOIN大学ûON U.IdUniversity = CU.IdUniversity;
        字符串CONNSTRING =数据库= yourDB;服务器= yourServer; UID =用户; PWD =密码;;
        使用(SqlConnection的康恩=新的SqlConnection(CONNSTRING))
        {
            字符串strQry =;
            使用(的SqlCommand objCommand =新的SqlCommand(srtQry,康涅狄格州))
            {
               objCommand.CommandType = CommandType.Text;
               DataTable的DT =新的DataTable();
               SqlDataAdapter的ADP =新SqlDataAdapter的(objCommand);
               conn.Open();
               adp.Fill(DT);
               如果(DT!= NULL)
               {
                  。名单= dt.AsEnumerable()了ToList();
               }
            }
        }
        返回列表;
    }

请该GetCustomers的方法返回的数据行的名单。不是你的自定义域的实体。 实体框架是给你的域实体的列表。因此,在自定义SQL的情况下,你需要将数据行映射到您的自定义对象自己的一个实例。

使用LINQ,你可以的DataRow的列表转换为您的自定义对象像这样

 公众的ActionResult指数()
{
   变种项= GetCustomers的();   变种newItems =(从项p
                       新选择
                       {
                           名称= p.Field<串GT;(姓名),
                           CampusName = p.Field<串GT(CampusName)
                       })了ToList()。    返回查看(newItems);
}

这会给你有2个属性匿名类型,名称 CampusName 的列表。假设名称和CampusName在你的查询结果2列present。

EDIT2:根据注释,在视图中列出这些数据上,下视图中创建一个名为指数控制器内(在这里我们写这个action方法)查看文件夹Folder.We需要做它强类型的视图。可是等等!我们要什么类型的传递给看法?

我们的结果是annonymous类型。因此,我们将在这种情况下创建一个视图模型和替代annonymous,我们将返回视图模型的列表。

 公共类UniversityViewModel
{
  公共字符串UniversityName {集;获取;}
  公共字符串CampusName {集;获取;}
}

现在,我们将在我们这样Index操作更新code。

  VAR newItems =(从项目p
                 选择新UserViewModel
                 {
                    UniversityName = p.Field<串GT;(姓名),
                    CampusName = p.Field<串GT(CampusName)
                 })了ToList()。

唯一的变化是现在我们这里提到的一个类型。所以输出是没有更多annonymous类型。但已知类型。

让我们回到我们的观点和写入code这样的。

  @model IEnumerable的< SO_MVC.Models.UserViewModel>
@foreach(以型号VAR项)
{
   &所述p为H.; @item .UniversityName @ item.CampusName&下; / P>
}

这观点是强类型我们的视图模型的集合。像往常一样,我们循环直通的和显示。这应该很好地工作。据测试。

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 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.

这篇关于如何使用SQL正常在ASP.NET MVC中没有EF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆