views:

145

answers:

2

Hey,

I'm new to linq and I'm trying to write an update statement.

I have two tables, tblProject and tblPage. the two are linked via a foreign key in tblPage.

So when trying to create a row in tblPage this it th inq query I have

    public void CreatePage(int projectId, string pageName, DateTime createdDate, int createdBy, DateTime updatedDate, int updatedBy)
    {
        using (EverythingEngineEntities db = new EverythingEngineEntities())
        {
            Page page = new Page();
            page.Project = db.ProjectSet.Single(p => p.ProjectId == projectId);
            page.LastUpdatedBy = updatedBy;
            page.LastUpdatedDate = updatedDate;
            page.CreatedBy = createdBy;
            page.CreatedDate = createdDate;
            page.PageName = pageName;
        }
    }

What I want to know is this the correct way of inserting a row via linq to Entities.

Sorry if none of this makes sense :)

Edit:

I'm particulary interested if this line is the correct way

page.Project = db.ProjectSet.Single(p => p.ProjectId == projectId);
+2  A: 

You're almost done... you have to actually insert it though... (you've created it, which is step 1).

The code is something like:

db.Pages.InsertOnSubmit(page);
db.SubmitChanges();

I realize that's LINQ to SQL syntax there... but EF is pretty close.

EDIT: I was close... for EF it's

db.Pages.Add(page);

EDIT2: By the way, I forgot to mention that you don't have to hit the server if you're doing something as simple as above. I'm pretty sure you can do something like this in EF:

page.Project.ProjectID = projectID;

So you don't have to download the "db.ProjectSet.Single" just to re-insert it.

Timothy Khouri
Sorry, thats just me being slack and not adding it the code :S
Static Tony
A: 

I think your way is correct but your way will create an extra call.

You can replace

page.Project = db.ProjectSet.Single(p => p.ProjectId == projectId);


with

   page.ProjectReference.EntityKey = new EntityKey("EverythingEngineEntities.Project", "ProjectID", projectId);

Read this

Kuroro