实体框架 - 加入列表 [英] Entity Framework - Join to a List

查看:82
本文介绍了实体框架 - 加入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的数据库中检索与纯列表(而不是EF)中的项目列表相匹配的实体列表。实体框架4.1可以实现吗?

I need to retrieve a list of entities from my database that matches a list of items in a plain list (not EF). Is this possible with Entity Framework 4.1?

示例:

var list = new List<string> { "abc", "def", "ghi" };
var items = from i in context.Items
            where list.Contains(i.Name)
            select i;

这可以很好地返回匹配一个属性的行,但实际上有一个更复杂的属性: / p>

This works great to return rows that match one property, but I actually have a more complex property:

var list = new List<Tuple<string, string>>
{
    new Tuple<string,string>("abc", "123"),
    new Tuple<string,string>("def", "456")
};

// i need to write a query something like this:
var items = from i in context.Items
where list.Contains(new Tuple<string,string>(i.Name, i.Type))
select i;

我知道这是无效的,因为它会说它需要是一个原始类型,但是在那里任何方式做我想要完成的任务,或者我需要诉诸一个存储过程?

I know that is not valid because it will say it needs to be a primitive type, but is there any way to do what I'm trying to accomplish or will I need to resort to a stored procedure?

推荐答案

你有一个几个选项:

1)当然可以编写一个存储过程来做你需要的,并调用它。

1) You could, of course, write a stored procedure to do what you need and call it.

2)您可以将表读入内存,然后在内存列表中查询...这样您就不必使用原语:

2) You could read the table into memory and then query the in memory list...that way you don't have to use primitives:

var items = from i in context.Items.ToList()
            where list.Contains(new Tuple<string, string>(i.Name, i.Type))
            select i;


3)您还可以将查询转换为使用原语来实现相同的目标:

3) You could also convert your query to use primitives to achieve the same goal:

var items = from i in context.Items
            join l in list
            on new { i.Name, i.Type } equals 
                new { Name = l.Item1, Type = l.Item2 }
            select i;

只要表不是非常大,请随意选择第二个选项。否则,先走。

I would go with the second option as long as the table isn't extremely large. Otherwise, go with the first.

这篇关于实体框架 - 加入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆