使用实体框架中的另一个对象访问对象

时间:2017-04-20 11:07:43

标签: c# entity-framework

我有三个这样的课程:

public class Cancellations
{
    public int ID {get; set;}
    public string CustomerID {get; set;}
    public string CustomerName {get; set;}
}

public class Service
{
    public int ID {get; set;}
    public string CustomerID2 {get; set;}
    public string ServiceName {get; set;}
}

public class Bill
{
    public int ID {get; set;}
    public string CustomerID3 {get; set;}
    public string City {get; set;}
}

这些数据库中存在这样的关系:Service.ID=Cancellations.CustomerIDBill.CustomerID3 = Service.CustomerID2。 我想要实现的是,当我在Cancellations对象中拥有CustomerID时,如何才能获得正确的城市。你能给我一些提示吗?感谢。

2 个答案:

答案 0 :(得分:1)

假设您拥有CustomerID:

使用C#和Linq

using System.Linq;

--

// Suppose this is your cancellation object's CustomerID
int _customerID = 123;

--

var resultObj = from billObj in Bills 
            join serviceObj in Service on Service.CustomerID2 equals billObj.CustomerID3
            join cancellationObj in Cancellation on Cancellation.CustomerID equals serviceObj.ID
            where CancellationObj.CustomerID == _customerID
            select new { Bills = billObj };

--

String City = resultObj.Select(x => x.City).FirstOrDefault();

如果可能的话,我建议你给对象更有意义的名字。

答案 1 :(得分:1)

只是一个简单的加入:

var result = (from c in db.Cancellations
              join s in db.Service on c.CustomerID equals s.ID
              join b in db.Bill on s.CustomerID2 equals b.CustomerID3 
              select new { c.Id, c.CustomerName, b.City }).ToList();

2条建议:

  1. 重命名您的属性/类 - 感觉它们没什么意义
  2. 查找Navigation Propertires