“'学生'是一个名称空间,但在DbContext中声明DbSet时会像”类型“一样使用错误

时间:2017-03-16 20:01:34

标签: c# model asp.net-core entity-framework-core dbcontext

我正在尝试使用与命名空间同名的类来声明我的DbSet的{​​{1}}属性。

这是我的StudentDbContext代码

StudentDbContext

我尝试声明using Student.Web.Models; using Microsoft.EntityFrameworkCore; namespace Student.Web.StudentContext { public class StudentDbContext : DbContext { public StudentDbContext() { } public DbSet<Student> Students { get; set; } } } 的代码的最后一行是抛出错误消息:

  

'Student'是一个命名空间,但用作类型

这是我的名字命名模型

DbSet<Student>

我无法理解为什么会这样。我有一个名为namespace Student.Web.Models { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } } 的模型类。

.Net Core是否以不同方式处理命名空间?

2 个答案:

答案 0 :(得分:2)

如果命名空间与&之间存在冲突模型,在命名空间声明

中移动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; }
    }
}

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

这在C#中一直都是这样的,对于.NET Core来说并不是什么新鲜事。

原因是,当您拥有Student.Web.StudentContext的命名空间时,您可以访问Student.Web.StudentContextStudent.WebStudent中没有using的所有类型言。

但是在你的场景中,编译器不知道你是否想要引用Student(名称空间)或Student.Web.Models.Student类。

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

答案 1 :(得分:1)

听起来你有一个命名空间和一个名为Student的类。不是很好。为了解决这个问题,你可以在类名前加上命名空间;像Student.Student。但最好的想法是重命名命名空间我会说!

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