C# PostSharp方面:访问;注入;实体框架LINQ查询中的属性
我使用PostSharp aspects将属性“注入”到一些类中,这些类将存储(代码优先)在一个DB by Entity框架中。稍后,我想查询并访问查询中每个类的注入属性。 例如,假设我正在编写一个方面,将“id”属性注入到对象中:C# PostSharp方面:访问;注入;实体框架LINQ查询中的属性,c#,linq,entity-framework,postsharp,C#,Linq,Entity Framework,Postsharp,我使用PostSharp aspects将属性“注入”到一些类中,这些类将存储(代码优先)在一个DB by Entity框架中。稍后,我想查询并访问查询中每个类的注入属性。 例如,假设我正在编写一个方面,将“id”属性注入到对象中: interface IIdentifyable { string id { get; set; } } [IntroduceInterface(typeof(IIdentifyable))] [Serializable] public class Iden
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();
//引发异常
//LINQ to Entities无法识别方法IIIdentifiable Cast[Car,IIIdentifiable](Car)方法,并且无法将此方法转换为存储表达式。
dbContext.cars.Where(car=>Post.Cast(car.id.Contains(“1”)).Count();
//抛出异常
//IIIdentifiable不是用于类型筛选操作的有效元数据类型。类型筛选仅对实体类型和复杂类型有效。
dbContext.cars.OfType()。其中(car=>car.id.Contains(“1”)).Count();
//抛出异常
//无法将类型Car强制转换为类型IIIdentifiable。LINQ to实体仅支持强制转换EDM原语或枚举类型。
dbContext.cars.Where(car=>((iIdentifiable)car.id.Contains(“1”)).Count();
有没有办法做到这一点,或者根本没有办法以这种特殊方式将PostSharp与EF结合使用
谢谢。我不确定您的项目设置,但我假设所有内容都在同一个项目中:
您需要在单独的程序集中定义类。我认为不能在应用方面的同一项目中使用注入属性,因为我认为PostSharp发生在编译之后。您需要在一个新项目中执行Linq工作,该项目将引用编译后的输出 E.x.:
ProjectA生成的
Car
在数据库中是否有id
列?是的,有。数据库生成工作(令人惊讶)很好,完全符合预期。您需要在单独的程序集中定义类。我认为不能在应用方面的同一项目中使用注入属性,因为我认为PostSharp发生在编译之后。您需要在一个新项目中执行Linq工作,该项目将引用编译后的输出。E.x.:ProjectA啊,把这些类放到一个单独的程序集中应该是可行的!谢谢你的主意。只是出于进一步的好奇——我也尝试过用dynamic关键字找到一个解决方案,但我认为这个解决方案在LINQ查询中不起作用,对吗?@hjb417,你可以将其作为答案发布是的,没错。PostSharp在C#编译器完成后处理程序集,因此C#无法了解编织的内容。