[英]LINQ select with EF Core and cast to derived class without copying properties
I have a LINQ to select records from DB:我有一个 LINQ 从数据库中选择记录:
List<Companies> enabledCompanies;
using (var ctx = new NavigatorContextExt())
{
enabledCompanies = ctx.Companies
.Where(e => e.Enabled)
.ToList();
}
I have a CompaniesExt
class derived from Companies
class that contains a few extra properties to be calculated later.我有一个从
CompaniesExt
类派生的Companies
类,其中包含一些稍后要计算的额外属性。 I wish to have LINQ return CompaniesExt
classes.我希望 LINQ 返回
CompaniesExt
类。
I tried the following:我尝试了以下方法:
List<CompaniesExt> enabledCompanies;
using (var ctx = new NavigatorContextExt())
{
enabledCompanies = ctx.Companies
.Where(e => e.Enabled)
.Cast<CompaniesExt>()
.ToList();
}
But I got an InvalidCastException.但是我得到了一个 InvalidCastException。 Is this cast impossible to do?
这个演员是不可能做到的吗? Shall I just use LINQ to select into
CompaniesExt
and copy all properties by hand?我应该只使用 LINQ 选择到
CompaniesExt
并手动复制所有属性吗?
The actual runtime type of the entity you get from EF is Company
, so no, you can't magically cast that to a derived class.您从 EF 获得的实体的实际运行时类型是
Company
,所以不,您不能神奇地将其转换为派生类。
But it's not required to derive from an entity just to add some properties.但是不需要从实体派生只是为了添加一些属性。 Just use the
[NotMapped]
annotation in your entity itself:只需在您的实体中使用
[NotMapped]
注释:
public class Company
{
public int CompanyID {get;set;}
// ... other DB properties
[NotMapped]
public string SomeProperty { get; set; }
}
If your entities are generated, you can use a partial class to add the unmapped properties:如果生成了实体,则可以使用分部类来添加未映射的属性:
public partial class Company // other part in generated file
{
[NotMapped]
public string SomeProperty { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.