简体   繁体   中英

Fetch result from Raw SQL in asp.net MVC3

in controller

public ActionResult Index(int id)
{
    string sql = string.Format("SELECT * FROM emp WHERE empno = {0}", 3195);
    var ret = db.Database.SqlQuery<int>(sql).ToList();

     // I want to fetch above query result here...
     // Above query returns more than 1 rows and more than 1 column
     // Like ret.Column1(row0).value

    return RedirectToAction("Index");
}

how can I fetch result in the same function.. i need to perform some calculation here and saved the result in database again.

you need to do like this. Create a ViewModel:

public class EmployeeVM
{
public int Id {get;set;}
public string EmployeeName {get;set;}
}

action:

public ActionResult Index(int id)
{
    string sql = string.Format("SELECT Id,EmployeeName FROM emp WHERE empno = {0}", 3195);
    var ret = db.Database.SqlQuery<EmployeeVM>(sql).ToList();

     /
    return RedirectToAction("Index");
}

Remember that your model properties name should match the column name of the table, as in my case Id and EmployeeName property are mataching with column name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM