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

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

The number of primary key values passed must match number of primary key values defined on the entity.

我导航到这样做的具体记录:

@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);   
    }

有人知道为什么会出现这个错误?感谢帮助!

解决方法

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

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

在这种情况下,更改以下行:RecordDataView record = db.RecordDataView.Find(id);对于以下内容:RecordDataView recorddataview = db.RecordDataView.SingleOrDefault(m => m.Record_number == id);

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....