簡體   English   中英

了解Linq查詢的基本知識

[英]Understanding the basic for Linq queries

假設我的數據庫中有一個名為Table1 我在Table1有3列名為

FirstName
SurName
DOB

在sql中,我只需select * from Table1 ,它將顯示該特定表中的所有內容。 但是,我試圖理解的是如何使用C#中的Linq從該表中選擇所有值。 Table1位於數據庫中,並且前端使用ASP.NET和C#開發,我似乎對此不太了解。 我對linq了解很少,如果我犯了一個明顯的錯誤,請原諒

請參閱以下鏈接以獲取linq簡介

什么是Linq,它有什么作用?

http://weblogs.asp.net/scottgu/using-linq-to-sql-part-1

Linq提供了一種查詢數據的方法,但是您仍然需要提供一種Linq訪問該數據的方法-通過Linq2Sql類,ADO,實體框架等實現。

我是Entity Framework(EF)的粉絲,您可以在其中設置代表數據的對象,並使用上下文填充這些對象。

它可能看起來像這樣:

public class Table1
{
    public string FirstName { get; set; }
    public string SurName { get; set; }
    public DateTime DOB { get; set; }
}

public class Table1Repository
{
    private readonly MyEntities _context;

    public Table1Repository()
    {
        this._context = new MyEntities();
    }

    public IQueryable<Table1> Get()
    {
        return this._context.Table1; // in effect your "Select * from table1"
    }

    public IQueryable<Table1> GetById(DateTime dob)
    {
        return this._context.Table1.Where(w => w.DOB == dob); // pulls records with a dob matching param - using lambda here but there is also "query expression syntax" which looks more like sql
    }

}

請注意,您正在對表示數據而不是數據庫本身的上下文執行linq查詢。 Linq非常強大,但是您需要提供一種訪問數據的方法。 即使這些數據是xml,文件,數據庫,也可以!

在Linq2Sql中,您可以非常簡單地選擇所有字段

從數據上下文開始:

var db = new YourDataContext()

之后,您可以做類似的事情

var myData = from row
             in db.table1
             select row

正如您指出的那樣,您的知識太有限了。 查看有關L2S的系列文章: http ://weblogs.asp.net/scottgu/using-linq-to-sql-part-1

由於您使用的是EF6,因此可以使用LinqToEntity讀取表。

public ObservableCollection<Table1> ReadTable1()
{            
    using (YourDBContext dc = new YourDBContext())
    {
        var data = (from x in dc.Table1 
                    select x);

        return new ObservableCollection<Table1>(data);
    }            
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM