我今天尝试用2个类创建一个非常简单的dbcontext类" Class"和#34;学生"。启用迁移后,配置文件一直说它无法找到项目数据库中的模型的命名空间。
错误代码: CS0426类型名称'型号'类型'数据库'中不存在数据库C:\ Users \ rodney \ documents \ visual studio 2017 \ Projects \ SchoolManagementProtal \ Database \ Migrations \ Configuration.cs
DbContext类:
using System.Data.Entity;
namespace Database.Models
{
public class DbContext : System.Data.Entity.DbContext
{
public DbSet<Class> Classes { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Class>()
.HasMany(c => c.Students)
.WithMany(c => c.Classes);
}
}
}
迁移中的配置文件:
namespace Database.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Database.**Models**.DbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
}
班级实体:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Database.Models
{
public class Class
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string ClassName { get; set; }
[Required]
[Range(1, 100)]
public int MaxStudents { get; set; }
public int StudentId { get; set; }
public ICollection<Student> Students { get; set; }
}
}
学生实体
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Database.Models
{
public class Student
{
[Key]
public int Id { get; set; }
public int ClassId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
public Gender Gender { get; set; }
[Required]
public int TotalHours { get; set; }
[Required]
public int HoursStudied { get; set; }
public DateTime DateJoined { get; set; }
public ICollection<Class> Classes { get; set; }
public int HoursLeft
{
get
{
return this.TotalHours - this.HoursStudied;
}
}
}
}
我想我错过了某种类型的引用或其他东西。但即使在谷歌搜索一段时间后,我也无法找到任何解决方案。我在这里先向您的帮助表示感谢。干杯!
答案 0 :(得分:2)
System.Data.Entity.Database
类与您的Database
命名空间之间存在名称冲突,在这种情况下,该类优先,因此编译错误
您需要使用全局命名空间别名来解决它:
: DbMigrationsConfiguration<global::Database.Models.DbContext>
或者因为在这种特殊情况下,Database.Models
可以通过使用相对命名空间引用从Database.Migrations
直接访问:
: DbMigrationsConfiguration<Models.DbContext>