实体框架查询 [英] entity framework query

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

问题描述

我搜索了很多,但我找不到答案。

如何在实体框架中创建一个查询,以获取具有某些条件的表的所有记录。

i想要此查询有一些参数可以为null。

参数:字符串名称,int id

这些参数可以有值或null。

if name参数为null,不要使用这个条件。

怎么办呢?

提前谢谢

解决方案

< blockquote>我建​​议你阅读一些教程。例如:

- 使用EDM查询: [ ^ ]

- LINQ to Entities中的查询 [ ^ ]



根据您选择的查询技术,条件的表达方式不同。除此之外,有一个数据示例解释你所追求的内容会很有帮助。


一种方法是:

 public列表<  用户 >  SearchUsers( string userName,int?userId)
{
using(var ctx = new MyEntities())
{
IQueryable < 用户 > query = ctx.User;

if(userName!= null)
query = query.Where(u => u.Name.Contains(userName));

if(userId!= null)
query = query.Where(u => u.ID == userId.Value);

var users = query
.OrderByDescending(u => u.ID)
.ToList();

返回用户;
}
}


I Search a lot but i can not find answer.
how can create a query in entity framework that get all record of table with some condition.
i want to this query have some parameter that can be null.
parameter:string name,int id
these parameter can have value or null.
if name parameter is null,dont use this condition.
how can do it?
thank you in advance

解决方案

I would suggest going through some tutorials. For example:
- Querying with EDM:[^]
- Queries in LINQ to Entities[^]

Depending on the query technology you choose, the condition is expressed differently. Beyond that it would be helpful to have a data example explaining what you're after.


one way is:

public List<User> SearchUsers(string userName, int? userId)
{
    using (var ctx = new MyEntities())
    {
        IQueryable<User> query = ctx.User;

        if (userName != null)
            query = query.Where(u=>u.Name.Contains(userName));

        if (userId != null)
            query = query.Where(u=>u.ID==userId.Value);

        var users = query
            .OrderByDescending(u => u.ID)
            .ToList();

        return users;
    }
}


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

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