一般从实体框架返回一个项目

发布于 2024-10-18 06:28:47 字数 516 浏览 1 评论 0原文

我遇到过这样的情况:网站可以根据字符串从我的数据库中请求数据(不用担心 - 我正在防止 SQL 注入)。出于各种原因,我希望有一个方法可以返回用户期望的对象(从 EF)(最终通过部分页面返回)。

我在想这样的事情:

public <GenericType?> GetObject(int id, string typeName) {
  switch(typeName) {
    case "Type1":
      return db.Type1s.SingleOrDefault(t => t.TypeID == id);
    case "Type2":
      return db.Type2.SingleOrDefault(t => t.TypeID == id);
    default:
      return null;
  }
}

是否可以做这样的事情? (我试图避免的是必须提前执行 switch 语句,然后调用特定的存储库方法,因为这样我就必须重复代码并多次执行此操作。)

I have a situation where a website can ask for data from my database based on a string (don't worry - I'm protecting against SQL injections). For various reasons, I would like to have a single method which returns back the object (from EF) that the user expects (which, ultimately, comes back through a partial page).

I'm thinking something like this:

public <GenericType?> GetObject(int id, string typeName) {
  switch(typeName) {
    case "Type1":
      return db.Type1s.SingleOrDefault(t => t.TypeID == id);
    case "Type2":
      return db.Type2.SingleOrDefault(t => t.TypeID == id);
    default:
      return null;
  }
}

Is it possible to do something like this? (What I am trying to avoid is having to do the switch statement earlier and then call the specific Repository method because I would then have to repeat code and do this a number of times.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

原野 2024-10-25 06:28:47

CreateQuery 可能就是您所需要的。

实体框架是否具有与 DataContext 等效的功能。 GetTable来自 Linq2Sql (ObjectContext.CreateQuery?)

有没有什么方法可以获取要传入的所有可能类型,以与具有此 TypeID 属性的特定接口兼容?如果是这样,怎么样:

    public T GetResult<T>(int id, string typeName) where T : IClassWithTypeID {
        YourEntities db = new YourEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeName));

        return result.Single(t => t.TypeID == id);
    }

CreateQuery<T> might be what you need.

Does the Entity Framework have an equivalent of DataContext.GetTable<TEntity> from Linq2Sql (ObjectContext.CreateQuery<T>?)

Is there any way you can get all the possible types you'd be passing in to comport with a particular interface that has this TypeID property on it? If so, how about:

    public T GetResult<T>(int id, string typeName) where T : IClassWithTypeID {
        YourEntities db = new YourEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeName));

        return result.Single(t => t.TypeID == id);
    }
孤蝉 2024-10-25 06:28:47

实际上,任何类型的通用报告生成器/查询执行器/等都可能更适合直接 SQL 查询,而不是尝试将动态逻辑融入 EF 或 LINQ。

Practically speaking, any kind of generalized report generator / query executor / etc. is probably better served with direct SQL queries than trying to fit your dynamic logic into EF or LINQ.

一笔一画续写前缘 2024-10-25 06:28:47

我想手动将表达式树串在一起并不

    public T GetResult<T>(int id, string typeName) {
        AccrualTrackingEntities db = new AccrualTrackingEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeName));

        var param = Expression.Parameter(typeof(T));

        var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "TypeID"),
                Expression.Constant(id)),
            param);

        return result.Single(lambda);
    }

像我想象的那么难。

How about

    public T GetResult<T>(int id, string typeName) {
        AccrualTrackingEntities db = new AccrualTrackingEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeName));

        var param = Expression.Parameter(typeof(T));

        var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "TypeID"),
                Expression.Constant(id)),
            param);

        return result.Single(lambda);
    }

I guess manually stringing together an Expression tree isn't as hard as I thought it was.

情绪 2024-10-25 06:28:47

考虑到当你调用这个方法时事情会是什么样子......大概它看起来像这样:

object obj = GetObject(257, "Type1");

我想不出一种方法来使返回值的类型更具体,因为 EF 中的对象没有公共基类,它们也不实现公共接口。当然,您可以让他们实现这样的接口(正如 Adam 建议的那样,尽管目的不同),然后像这样重写您的方法: 然后

public IMyInterface GetObject(int id, string typeName) {
    switch(typeName) {
        case "Type1":
            return (IMyInterface)db.Type1s.SingleOrDefault(t => t.TypeID == id);
        case "Type2":
            return (IMyInterface)db.Type2.SingleOrDefault(t => t.TypeID == id);
        default:
            return null;
    }
}

您的调用代码将如下所示:

IMyInterface intf = GetObject(257, "Type1");
intf.DoSomethingHelpful();

当然,我对您的调用代码的猜测可能是离得很远。

Considering how things will look when you call this method...presumably it would look something like this:

object obj = GetObject(257, "Type1");

I can't think of a way to make the type of the returned value more specific, because objects in the EF don't have a common base class, neither do they implement a common interface. Of course, you could make them implement such an interface (as Adam suggests, though with a different purpose), and then rewrite your method like this:

public IMyInterface GetObject(int id, string typeName) {
    switch(typeName) {
        case "Type1":
            return (IMyInterface)db.Type1s.SingleOrDefault(t => t.TypeID == id);
        case "Type2":
            return (IMyInterface)db.Type2.SingleOrDefault(t => t.TypeID == id);
        default:
            return null;
    }
}

Then your calling code would look like this:

IMyInterface intf = GetObject(257, "Type1");
intf.DoSomethingHelpful();

Of course, my guess at your calling code may be way off.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文