Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架-列名“CourseLesson_Id”无效_C#_Entity Framework - Fatal编程技术网

C# 实体框架-列名“CourseLesson_Id”无效

C# 实体框架-列名“CourseLesson_Id”无效,c#,entity-framework,C#,Entity Framework,尝试执行以下查询后: List<CourseLesson> courseLessons = (from cl in context.CourseLessons .Include(x => x.CourseLessonTestQuestions) select cl).ToList();

尝试执行以下查询后:

List<CourseLesson> courseLessons = (from cl in context.CourseLessons
                                                .Include(x => x.CourseLessonTestQuestions)
                                                select cl).ToList();
我在无效列名“CourseLesson_Id”中收到错误消息

我的模型和DataContext看起来像这样,这来自于我创建的一个测试项目,以减少问题

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; }
}
我有两个外键指向同一个表,我假设EF试图创建或映射一些不存在的东西

在阅读了一段时间后,我找到了一种方法,可以使用以下代码修复中的问题:

            modelBuilder.Entity<CourseLessonTestQuestion>()
                .HasOptional(cltq => cltq.ReturnCourseLesson)
                .WithMany(x => x.CourseLessonTestQuestions);
这种情况真正让我感到不安的是,为什么当我使用fluentapi时,一切都能正常工作,但它不能与ForeignKey属性一起工作?这看起来可能会导致未来的问题,我想知道到底发生了什么

真正的问题是,没有fluentapi,有没有解决这个问题的方法?比如使用属性或其他约定


我使用的是实体框架6.1.3

解决方案,没有Fluent API,但借助InversePropertyAttribute,其构造函数的参数是相应CourseLessonTestQuestion属性的名称:

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; }    
}

@AntonMaiorov如何使用nameof引用另一个类中的属性?我指的是课程名称SonTestQuestion.CourseLesson而不是CourseLesson。同样适用于ReturnCourseLesson