在我的场景中,我有两张桌子,比如员工和经理。并使用第一种方法。
以下是Employee和Manager类代表Employees和Managers表对象。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<TABLE BORDER="3" CELLPADDING="10" CELLSPACING="10">
<input type="checkbox" id = "Select_All" name="Main" />Select All Information
<TD>
<input type="checkbox" id = "Parent_Id" name="PPP" class = "Parent_Class" />parent
<TABLE BORDER="3" CELLPADDING="3" CELLSPACING="3">
<div>
<TD>
<input type="checkbox" id = "Child_Id" name="CCC" class = "Child_Class" /> Child1 </TD>
<TD>
<input type="checkbox" id = "Child_Id" name="CCC" class = "Child_Class" />Child2</TD>
<TR>
<TD>
<input type="checkbox" id = "Child_Id" name="CCC" class = "Child_Class" /> Child3</TD>
<TD> <input type="checkbox" id = "Child_Id" name="CCC" class = "Child_Class" />Child4
</TD>
</TR>
</div>
</TABLE>
</TD>
<TD> <input type="checkbox" id = "Child_Id" name="CCC" class = "Child_Class" />
A table inside a table.</TD>
</TABLE>
以下是代码段;我用来根据员工是否是经理来保存员工和经理表中的记录。
public abstract class BaseEmployee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public long EmployeeId { get; set; }
public string Address { get; set; }
}
[Table("Employees", Schema = "EmployeeData")]
public partial class Employee: BaseEmployee
{
}
[Table("Managers", Schema = "EmployeeData")]
public partial class Manager: BaseEmployee
{
[Column("ManagerId")]
public override long EmployeeId { get; set; }
}
}
直到这里它运作正常。现在我想在两个表中保存Manager,即Manager和Employee表。
并想做类似下面的事情:
BaseEmployee employeeRow;
if (IsManager)
{
Manager= new Manager();
}
else
{
employeeRow= new Employee();
}
//Do some stuff
if (IsManager)
{
context.Managers.Add(employeeRow as Manager);
context.SaveChanges();
}
else
{
context.Employees.Add(employeeRow as Employee);
context.SaveChanges();
}
但是在将employeeRow转换为Employees时会抛出异常,这很明显,因为我们在经理的情况下使用Manager类实例化employeeRow。我可以通过与Manager对象并行创建一个类型为Employee的对象来处理这种情况,但这对我来说似乎不对。
有人可以建议我如何最好地利用OOPS来处理这种情况吗?
感谢。