LINQ结合两个表

时间:2013-08-09 05:08:51

标签: asp.net-mvc linq

目前我有2个数据库表,如下所示:

---------------        --------------------
|  Categories |        |  Item_Categorys  |
---------------        --------------------
|      id     |        |        id        |
|     Title   |        |   Category_ID    |
---------------        |      Item_ID     |
                       --------------------

我有一个模型,在我的视图上显示复选框,就像

LocalCategoryModel
-------------------
int categoryid
string category_title
bool ischecked

我正在尝试从表中获取所有项目类别,然后获取所有类别行,然后交叉检查它们到哪里有一个类别项目,它将它放在IEnumerable中。所以最后,LocalCategory具有所有类别,然后将缺陷设置为true或false,具体取决于它是否在Item_Categorys sql表中有一行。

3 个答案:

答案 0 :(得分:1)

public class LocalCategoryModel
    {
        public int categoryid { get; set; }
        public string category_title { get; set; }
        public bool ischecked { get; set; }
    }

public IEnumerable<LocalCategoryModel> getSourec()
        {
            IEnumerable<LocalCategoryModel> query = from tbcat in Categories
                        join tbitem_cat in dc.Item_Categorys
                        on  tbcat.id equals tbitem_cat.Category_ID into ct
                        from tbitem_cat in ct.DefaultIfEmpty()
                        select new LocalCategoryModel
                        {
                            categoryid = tbcat.id,
                            category_title = tbcat.Title,
                            ischecked = tbitem_cat == null ? false : true
                        };

            return query;
        }

答案 1 :(得分:0)

我会给你一些例子。

它可以帮助你。

我指的是一本名为'C#4.0 IN A NUTSHELL'的书。


// outer collection
customers.Join (
      purchases,                  // inner collection
      c => c.ID,                  // outer key selector
      p => p.CustomerID,          // inner key selector
      (c, p) => new { c, p } )    // result selector
  .OrderBy (x => x.p.Price)
  .Select  (x => x.c.Name + " bought a " + x.p.Description);

 from c in customers
 join p in purchases on c.ID equals p.CustomerID
 select new { c.Name, p.Description, p.Price };

答案 2 :(得分:0)

class Category { public int id; public string Title; };
class CategoryItem { public int category_id; public int item_id; }
class Category { public int id; public string title; };

// Create categories list
var categories = new List<Category>() { new Category { id = 1, title = "First" }, new Category { id = 2, title = "Second" } };

// Create categories items list
var categories_items = new List<CategoryItem>() { new CategoryItem { category_id = 1, item_id = 2 } };

// All categories in categories_items
var categories_items_set = categories_items.Select(x => x.category_id).Distinct();

// Final query
var q = categories.Select(x => new { categoryid = x.id, category_title = x.title, ischecked = categories_items_set.Contains(x.id) });
q.ToList()

// output
categoryid = 1, category_title = First, ischecked = True
categoryid = 2, category_title = Second, ischecked = False