带有Code First EF的实体之间关系的错误

时间:2016-04-29 16:34:00

标签: c# asp.net entity-framework ef-code-first entity-relationship

我正在为我所在大学的项目构建一个ASP.NET Web应用程序。对于如何使用Code First Entity Framework(.NET)配置实体之间的关系,我看起来简单易行。只要我想'add-migration -name',就会出现第一个错误。我理解这个概念有些错误。

如下所示:

在我的情况下,我有6个实体也与彼此有关系。

我的会话实体与其他类有以下关系:

[Table("Session")]
public class Session
{
    [Key()]
    public Guid Id { get; set; }
    //non-relevant properties
    [ForeignKey("StudentsAttention")]
    public Guid StudentsAttentionId { get; set; }
    [ForeignKey("Course")]
    public Guid CourseId { get; set; }
    [ForeignKey("Klas")]
    public Guid KlasId { get; set; }
    public virtual Teacher Teacher { get; set; }
    public virtual Course Course { get; set; }
    public virtual Klas Klas { get; set; }
    public virtual StudentsAttention StudentsAttention { get; set; }
}

Klas实体:

[Table("Klas")]
public class Klas
{
    [Key()]
    public Guid Id { get; set; }
    //not relevant
    public virtual ICollection<Student> Students { get; set; }
}

课程实体:

[Table("Course")]
public class Course
{
    [Key()]
    public Guid Id { get; set; }
    //not relevant
    [ForeignKey("Session")]
    public Guid SessionId { get; set; }
    public virtual Session Session { get; set; }
}

教师实体:

[Table("Teacher")]
public class Teacher
{
    [Key()]
    public Guid Id { get; set; }
    //not relevant
    [ForeignKey("Session")]
    public Guid SessionId { get; set; }
    public virtual Session Session { get; set; }
}

学生实体:

[Table("Student")]
public class Student
{
    [Key()]
    public Guid Id { get; set; }
    //not relevant
    [ForeignKey("Klas")]
    public Guid KlasId { get; set; }
    [Required]
    public virtual Klas Klas { get; set; }
}

它给了我很多错误,但我相信大多数人会立即看到问题。所以我的问题是,如何修复实体关系?

如果两个实体具有一对多的关系,我会做下一件事:

public class EntityA
{
   public virtual ICollection<EntityB> EntityBs { get; set; }
}

public class EntityB
{
   [ForeignKey("EntityA")]
   public Guid EntityAId { get; set; }
   public virtual EntityA EntityA { get; set; }
}

一对一的关系:

public class EntityA
{
   [ForeignKey("B")]
   public Guid EntityBId { get; set; }
   public virtual EntityB B { get; set; }
}

public class EntityB
{
   [ForeignKey("A")]
   public Guid EntityA { get; set; }
   public virtual EntityA A { get; set; }
}

我确信像这样配置我的关系会给我带来多个错误。如何以正确的方式配置我的关系。我知道这可能已被问过100次,但这种帮助并没有解决我的问题。

0 个答案:

没有答案