views:

39

answers:

2

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

A: 

I would say you are unnecessarily retrieving the product. You could simply do something like:

var rating = entities.Ratings.First(r => r.product_id == pid);
if (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 
    entities.AddToRatings(rating);
}
entities.SaveChanges();
James
yes, Its a working code.. but is this the best way? I mean; can't I avoid the query that is executed in the beginning?
Abdel Olakara
@Abdel: Ah I see what you mean. I will update my answer.
James
@James Well.. I just learned that Single or SingleOrDefault is not supported by LINQ to Entities!!!
Abdel Olakara
@Abdel: It is available in EF 4.0, you never mentioned the version you were using. I am not sure there is an exactly equivalent in previous versions, the closes would be `First`, however, I am not sure if this will throw an exception if the query returns no results.
James
A: 

Whenever you are always going to load an entity, just do one round trip, and include it int he query that will get generated by EF.

    Product prod = entities
            .Product.Include("Rating")
            .First(p => p.product_id == pid);


    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();
Nix