I'm creating a new project using EF Power Tools and I get the following error:
Error
There was an error running the selected code generator:
'A configuration for type' TST2.Models.Course 'has already been added. To reference the existing configuration use the Entity () or ComplexType () methods.
I can work around the error (Generating View without a context), but I need to understand what I did wrong.
My entity follows:
public class Course
{
public Course()
{
this.StudentGrades = new List<StudentGrade>();
this.People = new List<Person>();
}
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual OnlineCourse OnlineCourse { get; set; }
public virtual OnsiteCourse OnsiteCourse { get; set; }
public virtual ICollection<StudentGrade> StudentGrades { get; set; }
public virtual ICollection<Person> People { get; set; }
}
Code for Mapping:
public class CourseMap : EntityTypeConfiguration<Course>
{
public CourseMap()
{
// Primary Key
HasKey(t => t.CourseID);
// Properties
Property(t => t.CourseID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(t => t.Title)
.IsRequired()
.HasMaxLength(100);
// Table & Column Mappings
ToTable("Course");
Property(t => t.CourseID).HasColumnName("CourseID");
Property(t => t.Title).HasColumnName("Title");
Property(t => t.Credits).HasColumnName("Credits");
Property(t => t.DepartmentID).HasColumnName("DepartmentID");
// Relationships
HasMany(t => t.People)
.WithMany(t => t.Courses)
.Map(m =>
{
m.ToTable("CourseInstructor");
m.MapLeftKey("CourseID");
m.MapRightKey("PersonID");
});
HasRequired(t => t.Department)
.WithMany(t => t.Courses)
.HasForeignKey(d => d.DepartmentID);
}
}
Context Code:
public class SchoolContext : DbContext
{
static SchoolContext()
{
Database.SetInitializer<SchoolContext>(null);
}
public SchoolContext()
: base(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True")
{ }
public DbSet<Course> Courses { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
public DbSet<OnlineCourse> OnlineCourses { get; set; }
public DbSet<OnsiteCourse> OnsiteCourses { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<StudentGrade> StudentGrades { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CourseMap());
modelBuilder.Configurations.Add(new DepartmentMap());
modelBuilder.Configurations.Add(new OfficeAssignmentMap());
modelBuilder.Configurations.Add(new OnlineCourseMap());
modelBuilder.Configurations.Add(new OnsiteCourseMap());
modelBuilder.Configurations.Add(new PersonMap());
modelBuilder.Configurations.Add(new StudentGradeMap());
}
}