我的关系像客户一样分层 - >地址 - >接触
单个客户可能有多个地址,而单个地址可能有多个联系人。看我的班级结构。
public class CustomerBase
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Customer : CustomerBase
{
public virtual List<Addresses> Addresses { get; set; }
}
public class Addresses
{
[Key]
public int AddressID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public bool IsDefault { get; set; }
public virtual List<Contacts> Contacts { get; set; }
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
public class Contacts
{
[Key]
public int ContactID { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public int AddressID { get; set; }
public virtual Addresses Customer { get; set; }
}
public class TestDBContext : DbContext
{
public TestDBContext()
: base("name=TestDBContext")
{
}
public DbSet<Customer> Customer { get; set; }
public DbSet<Addresses> Addresses { get; set; }
public DbSet<Contacts> Contacts { get; set; }
}
using (var db = new TestDBContext())
{
var customer = new Customer
{
FirstName = "Test Customer2",
LastName = "Test Customer2",
Addresses = new List<Addresses>
{
new Addresses
{
Address1 = "foo1",
Address2 = "foo2",
IsDefault=true,
Contacts = new List<Contacts>
{
new Contacts { Phone = "22222222", Fax = "1-999999999" }
}
}
}
};
db.Customer.Add(customer);
db.SaveChanges();
现在我想查询数据。假设我想要获取customerid is 1
并希望加载与客户ID相关的地址为1并且地址Isdefault为真且默认地址相关的联系人详细信息的客户。
我尝试以这种方式撰写它因此无法完成,因为我在EF和LINQ查询。
var bsCustomer = db.Customer.Where(c => c.CustomerID == 2).Include(a=>
a.Addresses.Where(a=> a.IsDefault==true)).Include(c=> c.)
所以请告诉我什么是查询,结果客户ID 1相关地址将加载其isdefault将为true并且将加载与地址相关的联系人。感谢
答案 0 :(得分:1)
您可以尝试如下所示。
基于查询的语法:
var dbquery = from cu in db.Customers
where (cu.CustomerID == 1)
select new {
cu,
Addresses= from ad in cu.Addresses
where (ad.IsDefault == true)
from ct in ad.Contacts
select ad,
};
您可以根据需要进行迭代:
var customers = dbquery.AsEnumerable()
.Select(c => c.cu);
foreach(var customer in customers )
{
foreach(var address in customer.Addresses)
{
//your code;
}
}
基于方法的语法:
var dbquery = db.Customers.Where(cu=>cu.CustomerID == 1)
.Select(cus=> new {
cus,
Addresses= cus.Addresses.Where(ad=>ad.IsDefault == true).Include(c=>c.Contacts)
}).AsEnumerable()
.Select(f => f.cus).ToList();