[英]Join Tables in Linq using lambda expression
I am working with Entity Framework. 我正在使用实体框架。 I have to apply join of two tables but what I want if there is one table Category
with a column categoryid
as foreign key which is of integer data type and another table Products
with column id
as primary key which is also of integer data type. 我必须应用两个表的联接,但是如果有一个表Category
具有列categoryid
作为外键(其是整数数据类型)和另一个表Products
具有列id
作为主键(也具有整数数据类型),我想要什么。
Now I need to select only those records from Products
table which have id
which is contained in Category
table. 现在,我只需要从Products
表中选择id
包含在Category
表中的那些记录。
This is my code: 这是我的代码:
string categoryid= "10,11,12";
datalist.DataSource = (from p in objCategory
join q in objProducts on p.categoryid.contains(q.id)
select new
{
p.FilePath,
p.ItemName,
p.Description,
q.image_url,
q.name,
q.price
}).ToList();
You could something like this: 您可以这样:
List<int> categoryIds = new List<int>(){ 10, 11, 12 };
datalist.DataSource = (from c in objCategory
join p in objProducts
on c.categoryid equals p.categoryid
where categoryIds.Contains(c.categoryid)
select new
{
c.FilePath,
c.ItemName,
c.Description,
p.image_url,
p.name,
p.price
}).ToList();
Instead of fetching all the data into memory and then join it's better to make navigation properties and fetch the data by these properties. 与其将所有数据都提取到内存中然后再进行合并,不如创建导航属性并通过这些属性来获取数据。 In this scenario all the join would work inside database and you will get only filtered data from database. 在这种情况下,所有联接都将在数据库内部工作,并且您只会从数据库中获取过滤后的数据。 Solution would work like 解决方案将像
class Category
{
public int CategoryId { get; set; }
public string Description{ get; set; }
public string FilePath {get;set;}
public string ItemName {get;set;}
public virtual ICollection<Product> Product{ get; set; }
}
class Product
{
public int ProductId { get; set; }
public string name{ get; set; }
public int CategoryId { get; set; }
public string Product.image_url {get;set;}
public int price {get;set;}
public virtual Category Category{ get; set; }
}
Now you just need to call the following query 现在您只需要调用以下查询
datalist.DataSource = (from p in objCategory.Include("Product")
select new
{
p.FilePath,
p.ItemName,
p.Description,
p.Product.image_url,
p.Product.name,
p.Product.price
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.