DbSet无法识别其实体

时间:2015-10-09 07:20:18

标签: c# entity-framework

我的DbContext类中的DbSet有问题。当我构建我的解决方案时,它给出了以下错误:

  

类型或命名空间名称'学生'找不到(你错过了使用指令或汇编引用吗?)

下面是我的DbContext类:

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

namespace CodeFirstMigration.Models
{
    public class StudentDbContext : DbContext
    {
        public StudentDbContext()
            : base("StudentDbContext")
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<StudentDbContext>());
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Department> Departments { get; set; }
    }
}

学生班:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace CodeFirst.Models
{
    public class Student
    {
        public Student()
        {

        }
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }

        [DataType(DataType.Date),
        DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
        public DateTime? DateOfBirth { get; set; }
        public string EmailId { get; set; }
        public string Address { get; set; }
        public string City { get; set; }

        public Department Department { get; set; } // Navigation Property
    }
}

系类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CodeFirst.Models
{
    public class Department
    {
        public Department()
        {

        }
        [Key]
        public int Id { get; set; }
        public string DepartmentName { get; set; }

        public List<Student> Students { get; set; } // Navigation property
    }
}

Student和Department类以及StudentDbContext都在同一个文件夹中。我尝试使用ProjectName.Models.Student和ProjectName.Models.Department但是徒劳无功。求救!

1 个答案:

答案 0 :(得分:1)

您的上下文存在于另一个名称空间中:

namespace CodeFirstMigration.Models

您是否尝试过将CodeFirst.Models语句添加到您的上下文中?

using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using CodeFirst.Models;

namespace CodeFirstMigration.Models
{
    public class StudentDbContext : DbContext
    {
        public StudentDbContext()
            : base("StudentDbContext")
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<StudentDbContext>());
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Department> Departments { get; set; }
    }
}