我正在编写一个应用程序,我们需要将一个基本实体扩展为许多不同的事物(例如员工、车辆等)。设计是这样的,有一个实体表和第二个具有特定类型值的表,例如,员工将有一个 ID 号,但车辆将有一个登记号。
我继承了数据上下文中生成的类实体,但在我的存储库中进行转换时遇到了问题。这样做的正确方法是什么?
public class cAccountEmployee : cAccountEntity
{
public string id_number
{
get
{
try
{
return this.cAccountEntityValues.Single(e => e.type == 1).value;
}
catch (Exception)
{
return "";
}
}
set
{
try
{
this.cAccountEntityValues.Single(e => e.type == 1).value = value;
}
catch (Exception)
{
this.cAccountEntityValues.Add(new cAccountEntityValue()
{
accountentity_id = this.id,
cAccountEntity = this,
type = 1,
value = value
});
}
}
}
然后在我的仓库中(不继承任何东西)
public IEnumerable<cAccountEmployee> All(int accountholder_id)
{
return db.cAccountEntities.Where(e => e.accountholder_id == accountholder_id).OrderBy(a => a.name).Cast<cAccountEmployee>();
}
public cAccountEmployee Single(int id)
{
return db.cAccountEntities.Single(a => a.id == id) as cAccountEmployee;
}
单一方法中的转换失败,因此我返回 null。据我了解,您不能从基类或向基类定义显式或隐式运算符?我怎样才能让基类 Linq 结果转换为继承的 Employee 类,同时仍然保持其数据库状态以便我可以提交更改?
最佳答案
对于 LINQ-to-SQL,继承有两种工作方式:
- 单个表的鉴别器(不适合,因为您的数据不是同质的)
- 基类/多表(并不是说 dbml 不支持 - 仅当您手动编写类时)
LINQ-to-SQL 不支持多表继承(即具有来自多个表的数据的单个对象)。 Entity Framework 可以,但更复杂;你用.Cast<T>
和 .OfType<T>
在 EF 中基于子类型进行转换/过滤。
你可能想看看:
- querying based on an ID (结合
GetTable<T>()
) - specifying a base-class in the dbml
这里基类的作用是什么?如果它添加了行为,那么您可以编辑 dbml 以为所有实体指定一个公共(public)基类。如果它具有数据属性,那么它会变得更加棘手。
就个人而言,我根本不会这样做......我会为不同的类型保留单独的类,并正确使用数据上下文,对每种类型使用单独的表:
public IEnumerable<Employee> All(int accountholder_id)
{
return db.Employees.Where(e => e.accountholder_id == accountholder_id)
.OrderBy(a => a.name);
}
public Employee Single(int id)
{
return db.Employees.Single(a => a.id == id);
}
所以 - 你能澄清一下 cAccountEntity
是什么吗?在这里吗?
关于c# - 继承 Linq to SQL 类并转换 linq 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/494884/