lambda表达式的实体框架组不起作用?

时间:2017-05-20 21:43:22

标签: c# entity-framework asp.net-mvc-4 lambda

我正在研究.net MVC很长一段时间。我想显示一个表格,我将一些列和组的总和发送给视图。我面临的问题=>(行动)

    public ActionResult Index()
    {
        TempData["UserDetails"] = db.UserDetails.Include(x => x.User).ToList();
        var financeofstudents = db.Financeofstudents.Include(f => f.Batche).Include(f => f.User).GroupBy(x => x.UserId).Select(x => new 
        {
            debit = x.Sum(item => item.debit),
            credit = x.Sum(item => item.credit),
            balance = x.Sum(item => item.balance)
        }).ToList();
        return View(financeofstudents);
    }

呀!可能是它的工作正常,但我不知道。因为我在客户端遇到了一些错误。

当我只是在客户端发送一个列表的工作文件时。似乎=>

var financeofstudents = db.Financeofstudents.Include(f => f.Batche).Include(f => f.User).ToList();

但是当我使用这个=>(因为我需要一个小组)==>

        var financeofstudents = db.Financeofstudents.Include(f => f.Batche).Include(f => f.User).GroupBy(x => x.UserId).Select(x => new 
        {
            debit = x.Sum(item => item.debit),
            credit = x.Sum(item => item.credit),
            balance = x.Sum(item => item.balance)
        }).ToList();

我得到的错误就像=> enter image description here

和我的观点=>

        @using TSMS_Atp_2_Final_Project.Models.Com.Tsms
        @model IEnumerable<Financeofstudent>

        @{
            ViewBag.Title = "Finance";
            IEnumerable<UserDetail> UserDetailsTable = TempData["UserDetails"] as IEnumerable<UserDetail>;    
        }

        <h2>Available Finance Detail Of Students...</h2>

        <p>
            <a href="@Url.Action("ASIB", "Batche")" class="btn btn-primary btn-sm">Assign New</a>
        </p>
        <div class="table-responsive">
            <table class="table table-striped table-inverse table-bordered">
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Batche.batch_code)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Batche.name)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.User.UserId)
                    </th>
                    <th>
                        @Html.Label("Full Name")
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.debit)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.credit)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.balance)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.lastTrunsaction)
                    </th>
                    <th></th>
                </tr>

                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.ActionLink(item.Batche.batch_code, "Details", "Batche", new { id = item.Batche.batch_code }, null)
                        </td>
                        <td>
                            @Html.ActionLink(item.Batche.name, "Details", "Course", new { id = item.Batche.name }, null)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.User.UserId)
                        </td>
                        <td>
                            @{
                                var UserDetailsId = UserDetailsTable.Where(x => x.UserId == item.User.UserId).Select(x => x.id).FirstOrDefault();
                                var FullName = UserDetailsTable.Where(x => x.UserId == item.User.UserId).Select(x => x.fullname).FirstOrDefault();
                            }
                            @Html.ActionLink(FullName, "Details", "Students", new { id = UserDetailsId }, null)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.debit)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.credit)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.balance)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.lastTrunsaction)
                        </td>
                        <td>
                            <div style="width:80px;">
                                @Html.ActionLink("Edit", "Edit", new { id = item.id }) |
                                @Html.ActionLink("Details", "Details", new { id = item.id }) |
                                @Html.ActionLink("Delete", "Delete", new { id = item.id })
                            </div>
                        </td>
                    </tr>
                }
            </table>
        </div>

然后我在网上搜索,发现我需要使用=&gt;

@model IEnumerable<System.Linq.IGrouping<object,Financeofstudent>>

的实例
@model IEnumerable<Financeofstudent> 

这......

我用过,也许问题解决了!但是之后我现在得到的错误就像=&gt; enter image description here 我试图找到解决方案并找到

The model item passed into the dictionary is 'System.Data.Entity.Infrastructure.DbQuery`, but requires 'System.Collections.Generic.IEnumerable

可能是它的解决方案,但我不理解任何事情。

我的模特=&gt;

    public class Financeofstudent
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    /// <summary>
    /// /////////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "User Id Is Required!")]
    [MaxLength(12, ErrorMessage = "The Max length Of User ID is 12 character!")]
    [RegularExpression("[1-3]{2}-[0-9]{5}-[123]{1}|[1-3]{2}-[0-9]{7}-[123]{1}", ErrorMessage = "Invalid Id,It should [xx]-[xxxxx]-[x] or [xx]-[xxxxxxx]-[x]!")]
    [Display(Name = "User ID")]
    public string UserId { get; set; }
    /// <summary>
    /// ////////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "Batch Code Is Required!")]
    [MaxLength(700, ErrorMessage = "The Max Length For Batch Code Is 700 Character!")]
    [Display(Name = "Batch Code")]
    public string batch_code { get; set; }
    /// <summary>
    /// ////////
    /// </summary>
    [Required(ErrorMessage = "Debit Is Required!")]
    [RegularExpression("^[0-9]*$", ErrorMessage = "Invalid Number!")]
    [Display(Name = "Debit Amount")]
    public int debit { get; set; }
    /// <summary>
    /// ////////
    /// </summary>
    [Required(ErrorMessage = "Credit Is Required!")]
    [RegularExpression("[0-9]*", ErrorMessage = "Invalid Number!")]
    [Display(Name = "Credit Amount")]
    public int credit { get; set; }
    /// <summary>
    /// /////////
    /// </summary>
    [Required(ErrorMessage = "Balance Is Required!")]
    [RegularExpression("[0-9]*", ErrorMessage = "Invalid Number!")]
    [Display(Name = "Current Balance")]
    public int balance { get; set; }
    /// <summary>
    /// //////////
    /// </summary>
    [DataType(DataType.Date, ErrorMessage = "Invalid Date!")]
    [Display(Name = "Last Trunsaction Date")]
    public DateTime lastTrunsaction { get; set; }

    [Display(Name = "Date Of Entry")]
    [DataType(DataType.DateTime, ErrorMessage = "Invalid Date!")]
    public DateTime entry_date { get; set; }

    ///relationship with anothere table

    [ForeignKey("UserId")]
    public User User { get; set; }
    /// <summary>
    /// ///////
    /// </summary>
    [ForeignKey("batch_code")]
    public Batche Batche { get; set; }
}

我期待像=&gt;

这样的东西

enter image description here

和query =&gt;

select UserId,sum(debit),sum(credit),sum(balance) from Financeofstudents group by UserId;
客户端上的

如上表所示?请帮助我。我可以解决我的问题。或者我做错了什么。或者还有其他方法来获得我的愿望。

3 个答案:

答案 0 :(得分:0)

您的组只返回3个整数的列表。该列表在他们根据您的视图建模时是过时的。您无权访问任何数据库对象属性。

基本上,执行的SQL只获取3个Sums的列表......

答案 1 :(得分:0)

看看这段代码:

.Select(x => new 
    {
        debit = x.Sum(item => item.debit),
        credit = x.Sum(item => item.credit),
        balance = x.Sum(item => item.balance)
    }).ToList();

它返回匿名类型,但您的视图使用了IEnumerable&lt; Financeofstudent&GT;模型。

尝试这样做:

创建类FinanceofstudentModel

class FinanceofstudentsModel
{
    public string UserId { get; set; }
    public int Debit { get; set; }
    public int Credit { get; set; }
    public int Balance { get; set; }
}

而不是将您的选择更改为此类

var financeofstudents = db.Financeofstudents
                          .Include(f => f.Batche)
                          .Include(f => f.User)
                          .GroupBy(x => x.UserId)
                          .Select(x => new FinanceofstudentsModel()
                                      {
                                          UserId = x.Key,
                                          Debit = x.Sum(item => item.debit),
                                          Credit = x.Sum(item => item.credit),
                                          Balance = x.Sum(item => item.balance)
                                      });

在您的视图中使用此模型

@model IEnumerable<FinanceofstudentModel>

您的观点可能如下所示:

@model IEnumerable<FinanceofstudentModel>
@foreach (var fm in Model)
{
    <p>User: @fm.UserId Debit: @fm.Debit Credit: @fm.Credit Balance: @fm.Balance</p>
    <hr/>
}

因此,您的模型只有4个属性(UserId,Debit,Credit和Balance)非常重要。如果要添加额外的属性,则应将其添加到FinanceofstudentModel中并填写控制器。

我希望这可以帮到你

答案 2 :(得分:-1)

创建一个类:

public class StudentFinance
{
    public double debit { get; set; }
    public double credit { get; set; }
    public double balance { get; set; }
}

将LINQ查询更改为

        var financeofstudents = db.Financeofstudents.Include(f => f.Batche).Include(f => f.User).GroupBy(x => x.UserId).Select(x => new StudentFinance
        {
            debit = x.Sum(item => item.debit),
            credit = x.Sum(item => item.credit),
            balance = x.Sum(item => item.balance)
        }).ToList();

现在最后,将视图上的模型更改为:

@model IEnumerable<StudentFinance>

这应该可以正常工作..如果能解决你的问题,请标记答案。