如何在模型优先EF中指定构图?

时间:2013-06-20 06:59:17

标签: c# .net entity-framework ef-model-first

我有以下域名。

  

角色是一个抽象类。程序员扩展角色。员工有多个角色,如程序员,经理等。

我想为它创建一个模型。我们如何在Employees实体中指定此composition角色?

注意:我无法在Roles表中添加EmpID。因为相同的角色适用于许多员工。

当前模式

enter image description here

所需概念模型的伪代码

public abstract class Role
{
    public abstract string RoleName { get; }
    public abstract int RoleID { get; }
}

public class ProgrammerRole : Role
{
    public override string RoleName { get { return "Programmer"; } }
    public override int RoleID { get { return 101; } }
}

public class ManagerRole : Role
{
    public override string RoleName { get { return "Manager"; } }
    public override int RoleID { get { return 102; } }
}


public class Employee
{
    private IList<Role> roles;
    public IList<Role> RolesList
    {
        get
        {
            return roles;
        }
    }


    public int EmployeeID { get; set; }

    //Constructor
    public Employee()
    {
        roles = new List<Role>();
    }

    public void TerminateEmployeeByRole(Role role)
    {
        if (RolesList == null)
        {
            //If employee has no role, make as inactive
            isActiveEmployee = false;
        }
        else
        {
            //If employee has no role other than the input role, make as inactive
            RolesList.Remove(role);
            if (RolesList.Count == 0)
           {
                isActiveEmployee = false;
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这可以通过更简单的方式实现:

public class Role
{
    public string RoleName { get; }
    public int RoleID { get; }
}

public class Employee
{
    public IList<int> RoleID { get; set; } // to store role id. This would form a table column
    [ForeignKey("RoleID")]
    public virtual IList<Role> RolesList { get; set; } // to reference Roles in the code. This will not for a table column

    public int EmployeeID { get; set; }

    //Constructor
    public Employee()
    {
        roles = new List<Role>();
    }

    public void TerminateEmployeeByRole(Role role)
    {
        if (RolesList == null)
        {
            //If employee has no role, make as inactive
            isActiveEmployee = false;
        }
        else
        {
            //If employee has no role other than the input role, make as inactive
            RolesList.Remove(role);
            if (RolesList.Count == 0)
            {
                isActiveEmployee = false;
            }
        }
    }
}

此设计的原因是,如果添加更多角色,您将无法创建更多类。您可以创建一个包装类来从数据库中获取角色详细信息。

  

请以此为出发点,而不是复制粘贴解决方案。