简体   繁体   English

asp.net从查询中获取数据

[英]asp.net getting data from a query

I have a simple asp.net database program. 我有一个简单的asp.net数据库程序。 I have a database called ChristmasTickets with data for: ID , BARCODENUM , NAME , EMAIL , ETC. 我有一个名为ChristmasTickets的数据库,其中包含以下数据: IDBARCODENUMNAMEEMAIL ,ETC。

I can do a simple find if someone searched ID because its the key identifier. 我可以做一个简单的查找,是否有人搜索ID,因为它是键标识符。

ChristmasTickets ChristmasTickets = db.ChristmasTicketsDb.Find(id);

But in my HTML I am attempting to allow a user to search by BarcodeNum and not the ID. 但是在我的HTML中,我试图允许用户通过BarcodeNum而不是ID进行搜索。 If the BarcodeNumber is found I am then trying to pull out the ID number. 如果找到了BarcodeNumber,则尝试提取ID号。

I have this code so far, which does give me some help. 到目前为止,我已经有了这段代码,这确实给了我一些帮助。

[HttpPost]
public ActionResult Search(SearchBarcode model, int BarcodeNum)
{         
var FoundRecord = db.ChristmasTicketsDb.Where(x => x.BarcodeNum == BarcodeNum);     

//get the ID from quote which does not work....


**int id = //get the id from FoundRecord.**
Trace.WriteLine("GET /ChristmasTickets/Edit/" + id);
if (id == null)
{
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ChristmasTickets ChristmasTickets = db.ChristmasTicketsDb.Find(id);
if (ChristmasTickets == null)
{
    return HttpNotFound();
}
    return View(ChristmasTickets);
}

Can someone please point me in the right direction on how to pull out the ID number from FoundRecord. 有人可以向我指出有关如何从FoundRecord中提取ID号的正确方向。

Thanks 谢谢

db.ChristmasTicketsDb.Where(x => x.BarcodeNum == BarcodeNum); Will give you an IQueryable of ChristmasTickets . 将为您提供IQueryable of ChristmasTickets

Supposedly, there is one or none of these. 据推测,这些都不是其中之一。

To get the actual element you are searching, you can use Linq FirstOrDefault() (or SingleOrDefault ) instead of Where : 要获取要搜索的实际元素,可以使用Linq FirstOrDefault() (或SingleOrDefault )代替Where

var christmasTicket = db.ChristmasTicketsDb.FirstOrDefault(x => x.BarcodeNum == BarcodeNum);

if (christmasTicket != null) 
{
    // found ! 
    // here you can take the id from christmasTicket

}

You can do it like this: 您可以这样做:

[HttpPost]
public ActionResult Search(SearchBarcode model, int BarcodeNum)
{         
    var FoundRecord = db.ChristmasTicketsDb.SingleOrDefault(x => x.BarcodeNum == BarcodeNum);         

    if (FoundRecord == null)
    {
        return HttpNotFound();
    }
    return View(FoundRecord);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM