在实体框架相同类型的多个集合 [英] Multiple collections of same type in entity framework

查看:95
本文介绍了在实体框架相同类型的多个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个非常简单的类。

I have these two very simple classes.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Group Group { get; set; }
}

public class Group
{
    public int Id {get;set;}
    public ICollection<Person> Teachers { get; set; }
    public ICollection<Person> Students { get; set; }
}



我想EF保持教师学生分开但是他们都得到混乱成表没有办法区分它们

I would like EF to keep Teachers seperated from Students however they both get jumbled into a Person table with no way to distinguish between them.

任何想法?

推荐答案

有两种方法可以做到这一点;

There are two ways to do it;

第一:使用在对象标记或枚举

first : use a tag or enums in the Person object

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Group Group { get; set; }
    public bool IsFaculty { get; set; }
}

public enum PersonType { Teacher, Student }; 

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Group Group { get; set; }
    public PersonType PropPersonType { get; set; }
}



第二:与继承导向的工作对象。此法有我的偏爱,因为它是易于管理,如果你想扩展它扩大。

second : work object oriented with inheritance. This method has my preference because it's easy to manage and expand if you want to expand it.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Group Group { get; set; }
}


public class Student : Person
{
    public int Year { get; set; }
    // other student related fiels.
}


public class Teacher : Person
{
    public List<Course> Courses { get; set; }
    // other teacher related fields
}

然后

public class Group
{
    public int Id {get;set;}
    public ICollection<Teacher> Teachers { get; set; }
    public ICollection<Student> Students { get; set; }
}

这篇关于在实体框架相同类型的多个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆