2012-08-12 90 views
0

我在网上搜索了这个问题的答案,没有运气。我有一个模型存在于使用实体框架创建的数据库中,并通过db(我的DBContext类的一个实例)进行访问。使用数据库查找主键以外的东西

Function Details(id As Integer) As ViewResult 
    Dim bill As Bill = db.Bills.Find(id) 
    Return View(bill) 
End Function 

对于纸币类的模型定义为:

Public Class Bill 

    Public Property BillId() As Integer 

    Public Property CustomerId() As String 

    Public Property BillStatus() As String 

End Class 

假设然后,在首先提到的函数I被传递的客户ID而不是这种模式的主键(BILLID),如何我会用这个来创建一个'Dim bill As Bill',它只包含那个customerId的账单。

正如上面的示例中,Bills被.Find(id)过滤的示例 - 仅查看主键 - 我希望能够对.Find()使用类似的方法,但是在非关键字段上: CustomerId在这种情况下。

回答

1

或者,如果您确定总是只有一个匹配该CustomerId的实体,则可以使用Single。

VB .NET

Dim myBill = db.Bills.Single(Function(x) x.CustomerId = cId); 

C#.NET

var myBill = db.Bills.Single(x => x.CustomerId == cId); 

注意,如果正好是1没有找到这会抛出异常。

0

使用.NET的过滤器的版本(如果)

Dim bills = db.Bills.Where(Function(x) x.CustomerId = cId) 

Dim bills = From i in db.Bills 
       Where i.CustomerId = cId 
       Select i 

编辑:每斯科特的评论调用FirstOrDefault()返回只有一个结果。如果不存在,则返回null。 要做到这一点。

Dim bill = (From i in db.Bills 
        Where i.CustomerId = cId 
        Select i).FirstOrDefault() 
If Not IsDBNull(bill) Then 
    /*Do Stuff*/ 
End If 
+1

请注意,这将返回一个列表(比尔)。您可以将.FirstOrDefault()的调用添加到任一端以获取单个Bill对象。你可以在这里阅读更多关于在VB.NET中使用的LINQ:http://msdn.microsoft.com/en-us/vstudio/bb688088.aspx – 2012-08-12 17:12:49

相关问题