您好,
我采用一个经典的例子,我有一个Customer
表和Purchase
表,一个客户可以有多个订单。
我创建了一个DBML
文件,然后从“服务器资源管理器窗口”中删除了两个表到DBML编辑器,生成了两个实体:Customers
和Purchases
我有一些对象:
public interface IMyCustomer
{
int Id { get; set; }
string Code { get; set; }
string Firstname { get; set; }
string Lastname { get; set; }
List<IMyPurchase> Purchases { get; set; }
}
public class MyCustomer : IMyCustomer
{
public int Id { get; set; }
public string Code { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<IMyPurchase> Orders { get; set; }
}
public interface IMyPurchase
{
int Id { get; set; }
string Code { get; set; }
DateTime CreationDate { get; set; }
}
public class MyPurchase : IMyPurchase
{
public int Id { get; set; }
public string Code { get; set; }
public DateTime CreationDate { get; set; }
}
var result =
from customer in _dataContext.Customers
join order in _dataContext.Purchases on customer.Id equals order.IdCustomer
select new MyCustomer
{
Code = customer.Code,
Firstname = customer.Firstname,
Lastname = customer.Lastname,
Id = customer.Id,
Purchases = _dataContext.Purchases
.Select(x => x.IdCustomer == customer.Id)
.Cast<IMyPurchase>()
.ToList<IMyPurchase>()
};
linq查询工作。对于结果条目,我拥有关于customer
的所有信息,我在Purchases
中有正确的行数,但Purchases
的每个条目的每个属性都为空。我想加载Customer
信息和所有purchase
有什么想法吗?
谢谢,
答案 0 :(得分:0)
您似乎在Purchase
和MyPurchase
之间没有任何翻译逻辑。
此外Cast<>()
方法将尝试使用隐式转换,但除非您的Linq-to-SQL实体实现该接口,否则无法以这种方式转换。
我的建议是使用AutoMapper之类的内容或在你的linq语句中添加翻译逻辑(类似于你对MyCustomer
所做的事情)。类似的东西:
var result =
from customer in _dataContext.Customers
join order in _dataContext.Purchases on customer.Id equals order.IdCustomer
select new MyCustomer
{
Code = customer.Code,
Firstname = customer.Firstname,
Lastname = customer.Lastname,
Id = customer.Id,
Purchases = _dataContext.Purchases
.Where(x => x.IdCustomer == customer.Id)
.Select(x => new MyPurchase {
Id = x.Id,
Code = x.Code,
CreationDate = x.CreationDate
}).ToList();
};
答案 1 :(得分:0)
以下是一个示例,以及您在购买中的客户ID
var items = (from p in _dataContext.Purchases
join c in _dataContext.Customers
on p.CustomerID equals c.ID
where (c.ID == customerId)
orderby p.CreationDate descending
select new { p, c });
foreach (var data in items)
{
// do stuff
int customerId = data.c.ID;
int purchaseId = data.p.ID;
// you can acces all properties of both objects
}