What is the best way in assigning foreign key when using entity framework & LINQ to Entities?

Posted by Abdel Olakara on Stack Overflow See other posts from Stack Overflow or by Abdel Olakara
Published on 2010-05-19T11:46:06Z Indexed on 2010/05/19 11:50 UTC
Read the original article Hit count: 315

Hi all,

I need to know the best practice of creating an entity object and assigning the foreign key. Here is my scenario. I have a Product table with pid,name,unit_price etc.. I also have a Rating table with pid (foregin key),rate,votes etc... Currently i am doing the following to create the rating object:

var prod = entities.Product.First(p => p.product_id == pid);

        prod.Rating.Load();
        if (prod.Rating != null)
        {
            log.Info("Rating already exists!");
            // set values and Calcuate the score
        }
        else
        {
            log.Info("New Rating!!!");
            Rating rating = new Rating();
            // set values and do inital calculation
            prod.Rating = rating;
        } entities.SaveChanges();

Even though this works fine, i would like to know the best practice in doing these kind of assignment.

Thanks for your suggestions and info.
Best Regards,
Abdel Olakara

© Stack Overflow or respective owner

Related posts about best-practices

Related posts about LINQ