mvc中的System.Data.Entity.Core.EntityException

时间:2017-03-19 09:20:38

标签: sql-server asp.net-mvc

我是mvc的新手。我在mvc。

中收到System.Data.Entity.Core.EntityException

我的模型文件包含以下代码:

    using System;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity;
    using System.Linq; 
    using System.Web;

   namespace demomvc.Models
   {
     [Table("Employee")]
     public class Employee
     {
       [Key]
       public int EmployeeId {get;set;}
       public string EmployeeName { get; set; }
     }
     public class DbClass : DbContext
     {
       public DbSet<Employee> employee { get; set; }
     }
   }

我的观点包含以下代码:

     @model IEnumerable<demomvc.Models.Employee>
     @using demomvc.Models;
     @{
         ViewBag.Title = "Index";
      }

      <h2>Employee</h2>
      @foreach(Employee emp in @Model)
     {  
         <li>
       @emp.EmployeeId;
       @emp.EmployeeName;
        </li>
     }

控制器是:

Error in Controller

Web.Config代码:

     <add name="DbClass" connectionString="Data Source=DIPS;
     Initial Catalog=dbo.Employee;Integrated Security=True"
      providerName="System.Data.SqlClient" /> 

SQL server Image:

SQL server Image

请帮我解决一个问题。

1 个答案:

答案 0 :(得分:1)

连接字符串必须指向您的数据库,而不是指向您的表:

<add name="DbClass" connectionString="Data Source=DIPS;Initial Catalog=dips;User ID=sa;Password=dips" providerName="System.Data.SqlClient" />

同时将该属性标记为virtual ::

public virtual DbSet<Employee> employee { get; set; }