我正在尝试确定使用Table-Per-Type层次结构的当前设计是否是我了解以下内容的最佳方式:
例如,我有3个子类(Manager,Executive,Employee)都继承自我的基础Person。然后,我想在网格视图中显示Person的所有实例,供最终用户选择,然后编辑其关联数据。但是,我的问题涉及在选择Person时如何查询适当的类型。我目前正在做的是Person类的以下内容:
public class Person
{
Guid PersonID { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
string PersonType { get; set; }
}
然后我在实例化每个子类时设置PersonType
字段。
将绑定和连线委托设置为SelectionChanged
事件
BindingSource peopleBinding = new BindingSource();
peopleBinding.DataSource = db.People.Local.ToBindingList();
this.peopleGridView.DataSource = peopleBinding;
this.peopleGridView.SelectionChanged += new EventHandler(peopleGridView_SelectionChanged);
GridView的SelectionChanged事件
if (peopleGridView.SelectedRows.Count != 1)
{
return;
}
Person person = peopleBinding.Current as Person;
if (person == null)
{
return;
}
switch (person.PersonType)
{
case "Employee":
Employee employee = db.Employees.Find(person.PersonID);
// Do Work With Employee
break;
case "Manager":
Manager manager = db.Managers.Find(person.PersonID);
// Do Work With Manager
break;
case "Executive":
Executive executive = db.Executives.Find(person.PersonID);
// Do Work With Executive
break;
default:
throw new ArgumentException (string.Format("Invalid type of person encountered ({0})", person.PersonType);
}
有没有更好的方法来获取子类的实例,而不是使用PersonType
字段作为某种鉴别器来确定我需要查询哪些DbSet
来获取相关实体?< / p>
答案 0 :(得分:2)
您可以使用is关键字:
if (person is Employee)
...
else if (person is Manager)
...
else if (person is Executive)
...
答案 1 :(得分:0)
如果你有(例如)DbSet<Person>
,你可以调用`OfType&lt;&gt;在上面。类似的东西:
Person person = db.People.OfType<Manager>().Find(PersonID);
修改强> 在TPT解决方案中,这也可以消除存储PersonType Discriminator的需要,假设您在其他地方不需要它。