开发者

mac var form linq to some instance

开发者 https://www.devze.com 2023-01-04 16:24 出处:网络
Hi if i create some instance of class products and then take 开发者_C百科one product from database using LINQ can i map result to this instance?

Hi if i create some instance of class products and then take 开发者_C百科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?


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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消