【问题标题】:The number of primary key values passed must match number of primary key values defined on the entity传递的主键值的数量必须与实体上定义的主键值的数量相匹配
【发布时间】:2015-01-24 20:45:40
【问题描述】:

我在 SQL Server 中创建了一个视图,其中包含来自不同表的最重要的列。 将表的内容打印到 ASP.NET MVC 视图可以正常工作,但是当我想获取单个记录的详细信息时,就会出现问题。

传递的主键值的数量必须与实体上定义的主键值的数量相匹配。

我这样做导航到特定记录:

@Html.ActionLink("Details", "Details", new {  id=item.Record_number  })

记录号是主键。我通过右键单击 .edmx 模型中的特定变量来手动设置它。然后我尝试使用以下方法获取特定数据:

    //
    // GET: /Record/Details/5
    public ActionResult Details(int id = 0)
    {
        try
        {
            RecordDataView record = db.RecordDataView.Find(id); //HERE THE ERROR OCCUR
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        catch(EntityException)
        {
            return RedirectToAction("NoDatabaseConnection", "Home");
        }
    }

模型看起来像这样:

namespace Implant.Database
{
    using System;
    using System.Collections.Generic;

    public partial class RecordDataView
    {
        public int Record_number { get; set; }
        public Nullable<System.DateTime> DOB { get; set; }
        public Nullable<System.DateTime> Record_date { get; set; }

        /** rest of code omitted */ 
    }
}

目前,我正在使用以下代码使其全部运行。但我不觉得这是一个很好的方式或效率。我很好奇如何解决上面的故障!

    //
    // GET: /Record/Details/5
    public ActionResult Details(int id = 0)
    {
        var record = from r in db.RecordDataView
                     select r;
        if (id != 0)
        {
            record = record.Where(r => r.Record_number == id);
        }
        RecordDataView rec = record.ToList().First(); 

        return View(rec);   
    }

有人知道为什么会发生此错误吗?感谢帮助!

【问题讨论】:

    标签: .net sql-server asp.net-mvc entity-framework edmx


    【解决方案1】:

    如果您在.edmx 中设置主键,您也应该更新您的数据库,因为您的模型中有PK 而不是您的数据库中。 更新:不适用于视图。

    对于视图,请使用 .SingleOrDefault 而不是 Find()

    在这种情况下,更改以下行:RecordDataView record = db.RecordDataView.Find(id); 致以下:RecordDataView recorddataview = db.RecordDataView.SingleOrDefault(m =&gt; m.Record_number == id);

    【讨论】:

    • 是否可以在数据库中的视图中添加主键?
    • 对不起,我以为您说您将 PK 添加到 edmx 文件中的普通表中以不查看。您是否尝试过 .SingleOrDefault 而不是 Find() ?
    • 工作就像一个魅力!非常感谢!然后我将以下行:RecordDataView record = db.RecordDataView.Find(id); //HERE THE ERROR OCCUR 更改为以下:RecordDataView recorddataview = db.RecordDataView.SingleOrDefault(m =&gt; m.Record_number == id); 再次感谢您!
    【解决方案2】:

    如果您的数据库表没有指定主键字段,您的 edmx 模型将假定每个字段都是一个键。所以确保你的数据库和你的实体模型说同样的话。

    如果您的模型和数据库正确指定了主键,那么您可以使用 .Find() 并且它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多