简体   繁体   English

在ASP.NET MVC中使用实体框架时出现问题

[英]Problem when using Entity Framework in ASP.NET MVC

I use Entities Framework to implement my data accsee layer in ASP.NET MVC. 我使用实体框架在ASP.NET MVC中实现我的数据访问层。 I got a problem in View. 我在View中遇到问题。

When my code in the VIEW something like: 当我的代码在VIEW中显示为:

I got an error in run time: 我在运行时出现错误:

Object reference not set to an instance of an object. 你调用的对象是空的。

Description: An unhandled exception occurred during the execution of the current web request. 说明:执行当前Web请求期间发生未处理的异常。 Please review the stack trace for more information about the error and where it originated in the code. 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

Source Error: 源错误:

Line 14: 第14行:

Line 15: <%= Model.FirstName %> Line 16: 第15行:<%= Model.FirstName%>第16行:

Line 17: 第17行:

This is generated from strong-typed view template. 这是从强类型视图模板生成的。 I ensured that I added model referrence to web.config I didn't encounter this error when I was using LINQ to SQL 我确保将模型引用添加到web.config中,而在使用LINQ to SQL时没有遇到此错误

Any help? 有什么帮助吗?

Since i can't comment on an answer i'll do it via a new answer.. I notice that your attribute is called "FirstName", are you by any chance trying to do this tutorial? 由于我无法对答案发表评论,因此我将通过一个新答案进行回答。.我注意到您的属性称为“名字”,您是否有机会尝试做教程? And is this the Edit action you're having problems with? 这是您遇到问题的“编辑”操作吗?

Because this is the exact same problem me and 2 of my classmates are having. 因为这是我和我的2个同学所遇到的完全相同的问题。 Here is a more detailed explanation of the problem: 这是对该问题的更详细说明:

This is the controller action: 这是控制器操作:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact contactToEdit) {
    if (!ModelState.IsValid)
        return View();

    try {
        var originalContact = (from c in base._entities.ContactSet
                               where c.Id == contactToEdit.Id
                               select c).First();
        base._entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
        base._entities.SaveChanges();

        return RedirectToAction("Index");
    } catch(Exception e) {
        return View();
    }
}

When the ApplyPropertyChanges is called an exception is raised. 调用ApplyPropertyChanges时会引发异常 (InvalidOperationException) Exception message: (InvalidOperationException)异常消息:

{System.InvalidOperationException: The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'ContactManager.Models.Contact'. {System.InvalidOperationException:ObjectStateManager不包含ObjectStateEntry,该对象对类型为'ContactManager.Models.Contact'的对象的引用。
at System.Data.Objects.ObjectContext.ApplyPropertyChanges(String entitySetName, Object changed) 在System.Data.Objects.ObjectContext.ApplyPropertyChanges(字符串EntitySetName,对象已更改)
at ContactManager.Controllers.HomeController.Edit(Contact contactToEdit) in C:\\Users\\Jeroen\\Desktop\\ContactManager\\ContactManager\\ContactManager\\Controllers\\HomeController.cs:line 65} 在C:\\ Users \\ Jeroen \\ Desktop \\ ContactManager \\ ContactManager \\ ContactManager \\ ContactManager \\ Controllers \\ HomeController.cs:line 65}中的ContactManager.Controllers.HomeController.Edit(Contact contactToEdit)处

When I add this line before ApplyPropertyChanges: 当我在ApplyPropertyChanges之前添加此行时:

System.Data.Objects.ObjectStateEntry x = base._entities.ObjectStateManager.GetObjectStateEntry(originalContact);

x does contain an entry of the correct type. x确实包含正确类型的条目。 ( debug image ) 调试图像

Note: I made a small deviation from the tutorial and put the entities object in a superclass so I don't have to declare the same object in all my controllers. 注意:我与本教程略有不同,将实体对象放入超类中,因此不必在所有控制器中都声明相同的对象。 But the same problem arises when following the tutorial. 但是,按照本教程进行操作时,也会出现相同的问题。

I figured it out! 我想到了! The problem was in the VIEW Normally, it would be, using (Html.BeginForm(new { Id = Model.Id })) 问题出在VIEW中,通常是使用(Html.BeginForm(new {Id = Model.Id}))

If the primary key in your database was CategoryID, you would think you should adapt the code to 如果数据库中的主键是CategoryID,则您认为应该将代码修改为

Id = Model.CategoryID ID = Model.CategoryID

BUT, actually, you should do it like this, 但实际上,您应该这样做

using (Html.BeginForm(new { CategoryID = Model.CategoryID })) 使用(Html.BeginForm(new {CategoryID = Model.CategoryID}))

Otherwise, it won't populate the model. 否则,它将不会填充模型。

Resurge, hope it helps! 喘口气,希望对您有所帮助!

Sometimes Model is null because the select statement with the method .FirstOrDefault() did not bring a valid object. 有时Model为null,因为带有.FirstOrDefault()方法的select语句未带来有效的对象。

You can always change .FirstOrDefault() to .First() and recompile your solution. 您始终可以将.FirstOrDefault()更改为.First()并重新编译您的解决方案。

It looks as though your Model is not populated properly in the controller. 看起来您的模型似乎未在控制器中正确填充。 There's not really enough information in your question to work out what exactly is going wrong though. 您的问题中没有足够的信息来确定到底出了什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM