从另一个表中获取ID

时间:2012-06-25 15:08:23

标签: c# .net linq

我正在尝试将产品添加到我的数据库中,我需要从另一个表中获取类别ID,但是我不知道我该怎么做?

基本上,我有一个包含所有不同类别的表格,我需要从我的外部网络服务中传递文本,然后点击数据库并获取其所需的猫的ID。 / p>

以下是我的代码:

using (aboDataDataContext dc = new aboDataDataContext())
{
    var match = (from t in dc.tweProducts
                 where t.sku == productSku
                 select t).FirstOrDefault();

    if (match == null)
    {
        tweProduct tprod = new tweProduct()
        {
            sku = p.productcode,
            categoryId = Convert.ToInt32(catid),
            title = p.name,
            brand = p.manufacturer,
            description = p.description,
            twePrice = p.price,
            weight = decimal.TryParse(p.size, out weight) == true ? (int?)weight : null,
            size = decimal.TryParse(p.size, out weight) == true ? (int?)weight : null,
            contry = p.country,
            region = p.region,
            vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null,
            strength = p.strength,
            bottler = p.bottler,
            age = int.TryParse(p.age, out age) == true ? (int?)age : null,
            caskType = p.casktype,
            series = p.series,
            flavour = p.flavour,
            stock = p.freestock,
            tweUpdated = false,
            stockUpdated = false,
            priceUpdated = false,
            dataUpdated = false,
            imgPublished = false,
            lastUpdated = DateTime.Now,
        };
    }
}

所以基本上Web服务的类别是在Category_1中传递(例如),我需要将它传递给我的数据库,以获取Category_1的ID(比如1)然后将其插入我的表中。

2 个答案:

答案 0 :(得分:2)

您需要使用FirstOrDefault(),假设您从Web服务获得有效而非空响应。

         categoryId = Convert.ToInt32((from c in dc.Categories
                                 where c.Name == p.category
                                 select c.Id).FirstOrDefault()),

答案 1 :(得分:1)

FirstOrDefault / First / SingleOrDefault / Single接受谓词:

categoryId = dc.Categories.Single(c => c.Name == p.category).Id;