帮助构建LINQ查询

时间:2009-10-08 14:20:27

标签: linq-to-sql c#-3.0

我有SQL数据库如下

alt text http://img97.imageshack.us/img97/5774/dbimage.jpg

现在我想过滤restaurant_detail表中的参数: 1.美食2.区域

你能帮我构建LINQ查询吗?

2 个答案:

答案 0 :(得分:0)

我假设你有一个使用LINQ to SQL或Entity Framework生成的模型。另外,我假设已经设置了外键关系。

var details = db
    .Cuisines
    .Where(c => c.Cuisine=="something")
    .SelectMany(c => c.RestaurantCuisines)
    .Select(rc => rc.Restaurant.RestaurantDetails)
    .Where(rd => rd.Area=="something")
;

答案 1 :(得分:0)

使用以下代码行完成linq查询:

            c = from q in dc.restaurant_cuisines
                    where q.cuisine.cuisine1.Contains(cuisine)
                        && q.restaurant.price.ToString().Length == price.Length
                    select new NearBy { NearById = q.restaurant.id, NearByLongitude = (double)q.restaurant.longitude, NearByLatitude = (double)q.restaurant.latitude };
        }
        int[] ids = new int[c.Count()];

var lon = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.longtitude;
        var lat = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.latitude;
        foreach(NearBy n in c)
        {
            result = calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), n.NearByLatitude, n.NearByLongitude);
            ids[i++] = n.NearById;
        }


        var r = from q in dc.restaurant_details
                where 1 == 1 &&
                (ids).Contains(q.restaurant_id)
                select new Restaurant
                {
                    Restora_id = q.restaurant_id.ToString(),
                    Name = q.restaurant.name,
                    Foodtype = q.restaurant.foodtype.foodtype1,
                    Avg_rating = q.restaurant.avg_rating.ToString(),
                    Featured = q.restaurant.featured.ToString(),
                    CuisineList = getCuisine(q.restaurant_id),
                    Restora_type = q.type,
                    Distance = Math.Round(calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), (double)q.restaurant.latitude, (double)q.restaurant.longitude), 2),
                    Newarrival = q.restaurant.newarrival.ToString(),
                    CountRecord = ids.Length.ToString()
                };
        var d = r.AsEnumerable().OrderBy(t => t.Distance);
        var g = d.Take(recordSize + 10).Skip(recordSize);
        return g.ToList();

请注意,上面显示的代码是根据初始要求的一些变化而生成的。