Reputation: 2528
I am trying to add a product to my DB, I need to get the category ID from another table, however i am not sure how i can do this?
Basically, i have a table with all my different categories in, and i need to pass over the text from my external web service, which will then hit the DB and get the ID of the cat its meant to be in.
Below is the code i have:
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,
};
}
}
SO basically the category from the web service is passing in Category_1 (for example), I need to pass this to my DB, to get the ID for Category_1 (say its 1) then insert it into my table.
Upvotes: 2
Views: 578
Reputation: 100248
FirstOrDefault/First/SingleOrDefault/Single accepts a predicate:
categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
Upvotes: 1
Reputation: 8062
You need to use FirstOrDefault(), assuming you are getting valid, not null response from your webservice.
categoryId = Convert.ToInt32((from c in dc.Categories
where c.Name == p.category
select c.Id).FirstOrDefault()),
Upvotes: 2