Linq到SQL获取多个列

Linq to SQL get multiple columns

本文关键字:获取 SQL Linq      更新时间:2023-09-26

我正在开发一个asp.net MVC web应用程序,在该应用程序中,我使用Linq到Sql通过jquery和ajax从数据库中获取结果。我的型号有以下代码

 public IEnumerable<string> getComments(long problemID)
        {
            var comment = from c in _objectModel.Comments
                          where c.ProblemID == problemID
                          select new { c.EmpID, c.CommentText, c.Time }.ToString();
            return comment;
        }

我的控制器有以下代码

public string GetComments(string problemid)
        {
            List<string> collection =  _discussionRepository.getComments(Convert.ToInt32(problemid)).ToList();
            string comments = null;
            foreach (string item in collection)
            {
                comments += item + "'n";
            }
            return comments; 

        }

在我看来包含

$("#btnPostComment").click(function () {
  var strdata = {
           problemID: $("#problemID").val(),
           commentText: $("#_1").val(),
           empID: $("#empID").val(),
           agree: 0,
           disagree: 0
        };
        $.ajax({
            type: "POST",
            url: "<%= Url.Action("PostComment", "Discussion")  %>",
            data: strdata,
  error: function(msg){
                alert("error" + msg);
            },
            success: function (msg) {
                var id = { problemid :  $("#problemID").val()};
                 $.ajax({
                    type: "GET",
                    url: "<%= Url.Action("GetComments", "Discussion")  %>",
                    data:  id,
                    error: function(msg){
                         alert("error2" + msg);
                    },
                    success: function (msg) {
                        $("#commentdiv").html(msg);
                    }
                    });

            }
        });

我在我的asp页面中得到了以下结果

{EmpID=1,CommentText=sss,Time=1/27/2012 2:27:49 AM}{EmpID=1,Comment Text=aaa,Time=1/227/27/2012 2:46:07 AM}{EmpID=1,CommentText=ss,Time=1/28/2012 12:35:00 PM}

我想得到没有括号和属性的结果,即1 ss 1/27/2012

问候

问题是您在匿名类型上调用ToString。您现有的Comment模型类是否包含太多数据?如果没有,您可以使用:

public List<Comment> GetComments(long problemID)
{
    return _objectModel.Comments.Where(c => c.ProblemID == problemID)
                                .ToList(); // Force evaluation
}

然后,您可以更改控制器,将这个List<Comment>转换为Javascript可以理解的AJAX。

如果真的只想要没有属性的字符串,您可以将原始代码更改为:

public IEnumerable<string> GetComments(long problemID)
{
    var query = from c in _objectModel.Comments
                where c.ProblemID == problemID
                select new { c.EmpID, c.CommentText, c.Time };
    return query.AsEnumerable() // Do the rest locally
                .Select(c => string.Format("{0} {1} {2"}, c.EmpID,
                                           c.CommentText, c.Time));
}

您还应该将控制器代码更改为使用String.JoinStringBuilder,否则由于重复的字符串连接,您将出现O(n2)问题。。。

查看客户端代码,您似乎期望从ajax调用中获得格式化的html,但您只是返回ToString(正如Jon Skeet所说)。

如果这是您的意图,那么您应该将字符串格式化为有效的HTML,但最好以json格式返回数据,并将其转换为HTML客户端。