在 DbContext 中声明 DbSet 时出现“'Student' 是一个命名空间,但像类型一样使用”错误

"'Student' is a namespace but is used like a type" error while declaring DbSet inside DbContext

我正在尝试使用与命名空间同名的 class 来声明我的 StudentDbContextDbSet 属性。

这是我的StudentDbContext代码

using Student.Web.Models;    
using Microsoft.EntityFrameworkCore;

namespace Student.Web.StudentContext
{
    public class StudentDbContext : DbContext
    {
        public StudentDbContext()
        {

        }

        public DbSet<Student> Students { get; set; }

    }
}

我试图声明 DbSet<Student> 的代码的最后一行抛出了错误消息:

'Student' is a namespace but is used like a type

这是我的带有命名空间的模型

namespace Student.Web.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

我不明白为什么会这样。我有一个名为 Student 的模型 class。

.Net Core 处理命名空间的方式不同吗?

听起来您有一个名称空间和一个名为 Student 的 class。不是很好。要绕过它,您可以在 class 名称前加上名称空间;喜欢 Student.Student。但最好的办法是重命名命名空间!

https://blogs.msdn.microsoft.com/ericlippert/2010/03/09/do-not-name-a-class-the-same-as-its-namespace-part-one/

当命名空间和模型之间存在冲突时,将 using 语句移到命名空间声明中

using Microsoft.EntityFrameworkCore;

namespace Student.Web.StudentContext
{
    // Move it here
    using Student.Web.Models;

    public class StudentDbContext : DbContext
    {
        public StudentDbContext()
        {

        }

        public DbSet<Student> Students { get; set; }

    }
}

namespace Student.Web.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

当编译器查找 class 时,它将首先使用内部使用,当找不到时,将搜索外部使用中的类型。

这在 C# 中一直以这种方式工作,并且在 .NET Core 中并不是什么新鲜事。

原因是,当您拥有 Student.Web.StudentContext 的命名空间时,您可以访问 Student.Web.StudentContextStudent.WebStudent 中的所有类型,而无需 [=11] =]声明。

但是在您遇到的情况下,编译器不知道您是想引用 Student(命名空间)还是 Student.Web.Models.Student class。

通过在其中移动 using 声明可以修复它,因为编译器会在 Student.Web.Models 命名空间内找到 Student 而不会向上查找(并以 Student 命名空间结尾)。