如何从表中获取所有链接的记录

问题描述 投票:0回答:3

我有一个带有表的MS SQL服务器,该表本身已链接

| Id| PreviousId|  Decription |
|---|:---------:|------------:|
| 1 | null      | Blah        |
| 2 | 1         | Blah        |
| 3 | 2         | Blah        |

而且我需要获取从ID = 3开始的所有记录的列表。

我的列表应类似于:

public class Record{
    public int Id {get;set;}
    public int? PrevId {get;set;}
    public string Desc {get;set;}
}
List<Record> records= new List<Record>();

/*Code to get all records*/

//Result
record[0] = Record(){Id=3,PrevId=2,Descr="Blah"} 
record[1] = Record(){Id=2,PrevId=1,Descr="Blah"} 
record[2] = Record(){Id=1,PrevId=null,Descr="Blah"} 

谢谢!

c# .net linq-to-sql
3个回答
0
投票

假设您的DbContext类似于:

public class MyDbContext : DbContext
{
   public MyDbContext(string connectionString) : base(connectionString) {}
   public DbSet<Record> Records {get; set;}
}

从表中检索记录的代码是:

var db = new MyDbContext(connectionString);
var records = db.Records.ToList();

或者,如果您想使用LINQ语法:

var db = new MyDbContext(connectionString);
var recordsQuery = from record in db.Records
                   select record;
var records = recordsQuery.ToList();

注意:由于问题是非常基本的,所以我建议您看一下EntityFramework文档或课程(IMO的朱莉·勒曼课程和书籍都很不错。]


0
投票

假设您的表被命名为Record,那么在您的模型(上下文类)中,您应该具有属性重设表调用的属性RecordRecords(如果您在模型中设置了复数名称)。因此,通过该属性可以从表中获取记录,您可以在该属性上使用常规的LINQ方法,例如Where

var result = dbContext.Records.Where(r => r.Id >= 3).ToList();

ToList()将导致查询执行。


0
投票

基于预期结果:

//Result
record[0] = Record(){Id=3,PrevId=2,Descr="Blah"} 
record[1] = Record(){Id=2,PrevId=1,Descr="Blah"} 
record[2] = Record(){Id=1,PrevId=null,Descr="Blah"} 

您正在尝试检索记录表中的所有数据。

我假设您正在使用实体框架。如果是,

您可以尝试这个。

using(YourDBContext db = new YourDBContext())
{
    records = db.records
     .Select(s=> new Record()
     {
       Id = s.Id,
       PrevId = s.PreviousId,
       Desc = s.Description,
     }).ToList();
}

或者如果我没记错的话,意味着所有数据> = 3。

 using(YourDBContext db = new YourDBContext())
 {
    records = db.records
     .Where(m=>m.Id >= 3)
     .Select(s=> new Record()
     {
       Id = s.Id,
       PrevId = s.PreviousId,
       Desc = s.Description,
     }).ToList();
 }
© www.soinside.com 2019 - 2024. All rights reserved.