【发布时间】:2014-08-25 22:31:39
【问题描述】:
我正在使用 PostSharp 方面将属性“注入”到某些类中,这些类将由实体框架存储(代码优先)在数据库中。稍后,我想在查询中查询和访问每个类的注入属性。 例如,假设我正在编写一个将“id”属性注入对象的方面:
interface IIdentifyable
{
string id { get; set; }
}
[IntroduceInterface(typeof(IIdentifyable))]
[Serializable]
public class IdentifiableAspect : InstanceLevelAspect, IIdentifyable
{
[Key]
[IntroduceMember]
public virtual string id { get; set; }
public override void RuntimeInitializeInstance()
{
id = Guid.NewGuid().ToString();
base.RuntimeInitializeInstance();
}
}
[Serializable]
[IdentifiableAspect]
public class Car
{
// ...
}
现在我想在实体框架 linq 查询中使用 Car 类的“注入”id 属性。例如,我想计算所有 id 包含数字 1 的汽车。 我尝试了几种方法,但都不起作用:
// Throws exception
// LINQ to Entities does not recognize the method IIdentifyable Cast[Car,IIdentifyable](car) method, and this method cannot be translated into a store expression.
dbContext.cars.Where(car => Post.Cast<Car, IIdentifyable>(car).id.Contains("1")).Count();
// Throws exception
// IIdentifyable is not a valid metadata type for type filtering operations. Type filtering is only valid on entity types and complex types.
dbContext.cars.OfType<IIdentifyable>().Where(car => car.id.Contains("1")).Count();
// Throws exception
// Unable to cast the type Car to type IIdentifyable. LINQ to Entities only supports casting EDM primitives or enumeration types.
dbContext.cars.Where(car => ((IIdentifyable)car).id.Contains("1")).Count();
有没有办法做到这一点,或者根本没有办法以这种特殊方式将 PostSharp 与 EF 结合使用?
谢谢。
【问题讨论】:
-
生成的
Car在数据库中有id列吗? -
是的,确实如此。数据库生成工作(令人惊讶)很好,完全符合预期。
-
您需要在单独的程序集中定义您的类。我认为您不能在应用方面的同一个项目中使用注入的属性,因为我相信 PostSharp 发生在编译后。你需要在一个引用编译输出的新项目中做你的 Linq 工作。例如:ProjectA
-
啊,将类放入单独的程序集中应该可以!谢谢你的主意。只是出于进一步的好奇-我也尝试使用 dynamic 关键字找到解决方案,但我认为它不适用于 LINQ 查询,对吗?
-
@hjb417,您可以将其发布为答案
标签: c# linq entity-framework postsharp