从实体替换属于另一个表

时间:2018-04-06 12:19:15

标签: c# entity-framework-core asp.net-core-mvc-2.0

我知道这个问题很糟糕,但这正是我无法找到答案的原因。

所以我有一个代表数据库表的实体(“TeacherEntity”)。其中一个属性表示映射到另一个表(“StudentEntity”)的外键。在(“教师”)表中,学生显示为数字。

public class TeacherEntity()
{
    public int TeacherId;
    public string Name;
}

public class StudentEntity()
{
    public int StudentId;
    public string StudenName;
    public int TeacherId;
}

我还有一个ViewModel类(“StudentViewModel”)。

public class StudentViewModel()
{
   public int Id;
   public string Name;
   public string TeacherName;
}

我想要实现的是当我用我的存储库读出学生列表时。

public List<TblShisha> GetStudents()
{
    return _context.StudentEntity.OrderBy(o => o.Name).ToList();
}

我应该提一下,我在我的Startup文件夹中使用AutoMapper,以防万一。

 cfg.CreateMap<Entities.StudentEntity, Models.StudentViewModel>()
     .ForMember(dest => dest.TeacherName, opt => opt.MapFrom(src => $" 
     {src.TeacherEntity.Name}"));

我希望为此学生提供教师的姓名,而不是他们的ID。 我是否必须读出学生名单并用控制器上的姓名替换教师ID,还是有更好的方法?

2 个答案:

答案 0 :(得分:2)

我会向Student添加一个类型为Teacher的属性。 然后在查询中,您可以执行以下操作:

_context.StudentEntity.Include("Teacher").OrderBy(o => o.Name).ToList();

然后,您可以使用Student.Teacher.Name

填充您的viewmodel

答案 1 :(得分:1)

可以通过设置带有两个表的DbContext来完成。

<强>上下文

public class TeacherStudentContext : DbContext
{
    public virtual DbSet<Student> Student { get; set; }
    public virtual DbSet<Teacher> Teacher { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"<connString>");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>(entity =>
        {
            entity.Property(e => e.Name).IsRequired();

            entity.HasOne(d => d.Teacher)
                .WithMany(p => p.Student)
                .HasForeignKey(d => d.TeacherId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Student_Teacher");
        });

        modelBuilder.Entity<Teacher>(entity =>
        {
            entity.Property(e => e.Name).IsRequired();
        });
    }
}

<强>教师

public class Teacher
{
    public Teacher()
    {
        Student = new HashSet<Student>();
    }

    public int TeacherId { get; set; }
    public string Name { get; set; }

    public ICollection<Student> Student { get; set; }
}

<强>学生

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int TeacherId { get; set; }

    public Teacher Teacher { get; set; }
}

现在您只需使用LINQ即可随时导航,而无需包含教师表。

var vm = _context.Student.Select(x => new StudentViewModel{
    Id = x.StudentId,
    Name = x.Name,
    TeacherName = x.Teacher.Name
});

或者您可以使用Automapper