如何在没有linq的ASP.NET MVC中使用原始普通SQL? [英] How to use raw normal sql in ASP.NET MVC without linq?

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

问题描述

我正在尝试使用ASP.NET MVC使用纯SQL编写一些代码.

I'm trying to write some code using pure SQL using ASP.NET MVC.

我认为我应该建立一个模型,并坚持使用MVC模式.

I assume I should be building a model, and sticking to the MVC pattern.

任何有关良好做法的建议都将受到高度赞赏,示例也非常有用.例如,我不确定是否应该将此代码从主存储库中分离出来,如果应该,应该将其放在哪里?

Any suggestions for good practice would be highly appreciated, and examples very useful too. For example I'm not sure if I should be splitting this code off from my main repository's, and if I should, where should I put it?

我还将尝试从该查询的2个表中返回数据.

Also I will be attempting to return data from 2 tables in this query.

我想使用的查询类型是这样的.

The kind of query I would like to use is like this.

查看此页面上的最佳答案

See top answer from this page

如何在SQL中实现高性能树视图Server 2005

string sqlGetQuestionAnswers = "SELECT TOP (10) * FROM tblquestion ORDER BY NEWID()";//

using (SqlDataAdapter dapQuestions = new SqlDataAdapter(sqlGetQuestionAnswers, ConfigurationManager.ConnectionStrings["SiteConnectionString"].ToString()))
        {
            DataSet dsQuestions = new DataSet();
            dapQuestions.Fill(dsQuestions);

            if (dsQuestions.Tables[0].Rows.Count > 0)
            {
               work with data;
        }

            else
            {
                Error;
            }
        }

推荐答案

鉴于您希望使用SQL MODEL方法,这可能对您有用.

Given you want a SQL to MODEL approach this might work for you.

我在这里使用LinqToSQL数据上下文;

I'm using a LinqToSQL data context here;

我有一个文章表,其中包含10个字段,但我只想标题,所以我创建了一个类;

I have a table of Articles that contains let's say 10 fields but all I want is the title so I create a class;

public class Art
{
  string title { get; set; }
}

然后我有我的数据上下文对象

Then I have my data context object

static ArticlesDataContext dc = new 
ArticlesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

然后我可以填充我的模型,尽管很简单;

Then I can fill my, albeit simple, model;

var arts = dc.ExecuteQuery<Art>(@"Select * from articles");

这对您有帮助吗?

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

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