Cur*_*ing 8 .net sql-server asp.net-mvc entity-framework edmx
我在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);   
    }
有人知道为什么会出现这个错误?感谢帮助!
Mar*_*cin 25
如果您设置主键,.edmx则应更新数据库,因为您的模型中有PK而不是数据库中的PK.  更新:不适用于视图.
对于视图使用.SingleOrDefault而不是Find().  
在此方案中,更改以下行:RecordDataView record = db.RecordDataView.Find(id); 
到以下内容:RecordDataView recorddataview = db.RecordDataView.SingleOrDefault(m => m.Record_number == id); 
| 归档时间: | 
 | 
| 查看次数: | 19236 次 | 
| 最近记录: |