DbSet不能识别它的实体
本文关键字:实体 识别 不能 DbSet | 更新日期: 2023-09-27 18:16:56
我在DbContext类中遇到了DbSet的问题。当我构建解决方案时,它给了我以下错误:
下面是我的DbContext类:类型或命名空间名称'Student'找不到(您是否缺少using指令或程序集引用?)
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,但无效。请帮助!
您的上下文位于另一个命名空间:
namespace CodeFirstMigration.Models
您是否尝试过添加使用CodeFirst。像这样在你的环境中建模?
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; }
}
}