tags:

views:

25

answers:

3

Hi if i create some instance of class products and then take one product from database using LINQ can i map result to this instance?

products produkt1 = new products();
var oneProduct= (from p in db.products where p.number == 640 select p)
                .FirstOrDefault();
produkt1 = oneProduct;

but of course it doesn't work , how should i do it?

A: 

Why don't you just edit the selected entity (oneProduct)?

Can you elaborate a little more on what your intention is -- do you want to create a duplicate of the selected entity for the purposes of inserting a new copy as a new row?

RobS
+1  A: 
products oneProduct = (from p in db.products
                      where p.number == 640
                      select p).FirstOrDefault();

or

products oneProduct = db.products.FirstOrDefault(p => p.number == 640);

You can't map instance from DB onto your, just created instance. You can save a reference to DB instance to your, i.e. replace:

 products produkt1 = new products(); // points to the first instance
 produkt1 = query.FirstOrDefault(...); // now points to the second instance. if this was the last reference, object probably will be deleted by GC soon

To map how you want isn't possible until your class supports this directly, i.e. via some method:

class products
{
    public void CloneFrom(products source)
    {
        this.SomeThing = source.SomeThing;
        ...
    }
}

in most case this is a bad idea, senseless approach.

abatishchev
+1 for the dot notation form, which is much simpler IMO. Query expressions are great where appropriate, but there's no reason to use it here.
Jon Skeet
A: 
products produkt1 =  db.products.FirstOrDefault(p => p.number == 640);
Femaref