简体   繁体   English

我可以为实体框架模型创建“中继”或“通用”属性吗?

[英]Can I create “relay” or “genericized” properties for Entity Framework models?

I hope my wording makes sense... I wasn't quite sure exactly how to explain what I'm looking to do. 我希望我的措辞是有道理的。。。我不确定如何解释我要做什么。

I have a method in a generic class that returns a list of entities as follows: 我有一个通用类中的方法,该方法返回实体列表,如下所示:

public abstract class ChildCRUDController<TModel> : CRUDController<TModel, ... >
    where TModel : IChildEntity

public ViewResult List(int id)
{
    return View(repository.GetMany(x => x.ParentID == id));
}

This controller is implemented by quite a few other controllers. 该控制器由许多其他控制器实现。 The issue I have is that not all entities that implement IChildEntity have the same parent type. 我的问题是,并非所有实现IChildEntity的实体都具有相同的父类型。 To get around this issue I created ParentID properties for all the models that implement IChildEntity so they could use the same controller. 为了解决这个问题,我为实现IChildEntity的所有模型创建了ParentID属性,以便它们可以使用同一控制器。

public partial class PhoneNumber : IChildEntity
{
    public int ParentID
    {
        get { return CustomerID; }
        set { CustomerID = ParentID; }
    }
}

and... 和...

public partial class Transaction : IChildEntity
{
    public int ParentID
    {
        get { return LeaseID; }
        set { LeaseID= ParentID; }
    }
}

But when I call the List method above I get the following error: 但是当我调用上面的List方法时,出现以下错误:

The specified type member 'ParentID' is not supported in LINQ to Entities. LINQ to Entities不支持指定的类型成员'ParentID'。 Only initializers, entity members, and entity navigation properties are supported. 仅支持初始化程序,实体成员和实体导航属性。

Is there any way I can achieve the result I am looking for without pulling the object set into memory or renaming all the properties on the entities themselves? 有什么方法可以在不将对象集拉入内存或重命名实体本身的所有属性的情况下实现所需的结果?

Thanks! 谢谢!

If you are willing to pass the field name into the List method and to construct your own query you can do it using the techniques described in this StackOverflow article: 如果您愿意将字段名称传递给List方法并构造自己的查询,则可以使用此StackOverflow文章中介绍的技术来做到这一点:

Or you could supply the ChildCRUDController with another generic type parameter constrained to an interface that supplies the field name and again use it dynamically. 或者,您可以为ChildCRUDController提供另一个通用类型参数,该参数限制在提供字段名称的接口上,并再次动态使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM