简体   繁体   中英

Entity Framework - Invalid column name 'CourseLesson_Id'

After trying to execute the following query:

List<CourseLesson> courseLessons = (from cl in context.CourseLessons
                                                .Include(x => x.CourseLessonTestQuestions)
                                                select cl).ToList();

I get the the error Invalid column name 'CourseLesson_Id'.

My models and DataContext looks like this(this is from a test project I've created to repreduce the problem)

public class CourseLesson
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public ICollection<CourseLessonTestQuestion> CourseLessonTestQuestions { get; set; }

}

public class CourseLessonTestQuestion
{

    public int Id { get; set; }

    public int CourseLessonId { get; set; }

    [ForeignKey(nameof(CourseLessonId))]
    public CourseLesson CourseLesson { get; set; }

    public int? ReturnCourseLessonId { get; set; }

    [ForeignKey(nameof(ReturnCourseLessonId))]
    public CourseLesson ReturnCourseLesson { get; set; }
}

I have 2 foreign keys that point to the same table and I'm assuming EF is trying to create or map something that doesn't really exist.

After reading for a while I've found a way to fix my problem in ( this answer ) with the following code:

            modelBuilder.Entity<CourseLessonTestQuestion>()
                .HasOptional(cltq => cltq.ReturnCourseLesson)
                .WithMany(x => x.CourseLessonTestQuestions);

What really bugs me about this situation is why everything works when I use the Fluent API, but it doesn't work with the ForeignKey attribute? This looks like something that could lead to future problems and I want to know what is really happening.

And the real question is there a solution for fixing this problem without the Fluent API? Like using attributes or some other convention?

I'm using Entity Framework 6.1.3

Solution without Fluent API, but with the help of InversePropertyAttribute , whose constructor's argument is the name of corresponding CourseLessonTestQuestion 's property:

public class CourseLesson
{
    public int Id { get; set; }    
    public string Title { get; set; }    
    public string Content { get; set; }

    [InverseProperty("CourseLesson")]
    public ICollection<CourseLessonTestQuestion> CourseLessonTestQuestions { get; set; }

    [InverseProperty("ReturnCourseLesson")]
    public ICollection<CourseLessonTestQuestion> ReturnCourseLessons { get; set; }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM