加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:35:01 所属栏目:asp.Net 来源:网络整理
导读:我在SQL Server中创建了一个视图,其中包含来自不同表的最重要的列. 将表的内容打印到ASP.NET MVC视图可以正常工作,但是当我想获取单个记录的详细信息时,就会出现问题. The number of primary key values passed must match number of primary key values def
我在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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读