0

I have a LINQ2SQL Query:

 //Pulling the Product_ID from the PlanMaster Table from WebEnroll DB!
                var tr = from s in dt.PlanMasters
                         where s.PlanName == productName
                         select new
                         {
                             s.Product_ID
                         };

This is pulling Product_ID which is working good. Now I want to ADD a record into another LINQ statement which is here:

                CommissionsV2DataContext cv = new CommissionsV2DataContext();
                Entity_Product_Point ev = new Entity_Product_Point();
                ev.Entity_ID = getEntity;
                ev.Product_ID = tr.; ?????

I want to store the variable which I am getting from tr (that is Product_ID) to ev.Product_ID.

How should I convert an object to an INT? Thank you!

0

4 Answers 4

5

The problem is that your first query returns a collection of objects with an integer property, not a single integer. You can change your query to this instead:

var tr = (
    from s in dt.PlanMasters
    where s.PlanName == productName
    select s.Product_ID).First();

Or, more cleanly, IMO:

var tr = dt.PlanMasters.First(s => s.PlanName == productName).Product_ID;
Sign up to request clarification or add additional context in comments.

2 Comments

I believe the second one still needs to call Select
Nope. First can take a delegate so that the first record that evaluates to true is returned.
3

tr is a collection. You have to call tr.FirstOrDefault().Product_ID.

Comments

1

I would change your linq query to select just the s.Product_ID instead of select newing a new anonymous object containing the ID.

 var tr = from s in dt.PlanMasters
          where s.PlanName == productName
          select s.Product_ID;

Your second code block could then be simply ev.Product_ID = tr.First();

  CommissionsV2DataContext cv = new CommissionsV2DataContext();
  Entity_Product_Point ev = new Entity_Product_Point();
  ev.Entity_ID = getEntity;
  ev.Product_ID = tr.First();

3 Comments

this won't work - tr is an IQueryable and not a number - you'll have to use i.e. tr.Single() assuming there is only one - otherwise the query is flawed.
or tr.First()... which is used.
Guess I hadn't refreshed the page - it wasn't there in the first version
0

ev.Product_ID = tr.First().Product_ID;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.