Michael
Michael

Reputation: 22957

Handle navigation properties when adding new object to entity model

I have the following data model:

enter image description here

I am writing a WCF service that needs to support adding new Report:

 public bool CreateNewReport(Report report)
    {
        MyEntities context = new MyEntities();
        context.AddToReports(Report);
        context.SaveChanges();
    }

So my method gets a report object that was made on the client and adds it to the database throught the data context. (all of the members are included in the DataContract)

My question is regarding navigation properties.

  1. Do the client also needs to create a user object and put it in the new report object before sending it ?
  2. What is the best way to approach this ? one way i think of is adding a UserId field in the ReportEntity
  3. when a new report is inserted, how do i update the UserEntity Report nav property that with the new Report ?

Thanks.

Upvotes: 2

Views: 1207

Answers (1)

Rico Suter
Rico Suter

Reputation: 11858

If you import your database, generate navigation properties (the properties in your picture) AND foreign id properties (then you have for example an User and UserID property in your report class). This way you can set the UserID in your client and send it to the server and add it with AddToReports... If you send the whole user object you have to attach it to the entity context otherwise the user will be created once again...

Attach the referenced user: (but it's better to send the user only by id)

public bool CreateNewReport(Report report)
{
    using (MyEntities context = new MyEntities())
    {
         context.AddToReports(Report);
         context.Users.Attach(report.User);
         context.SaveChanges();
    }
}

To change the report of a user:

public bool ChangeUserToNewReport(int userid, Report newReport)
{
    using (MyEntities context = new MyEntities())
    {
         var user = context.Users.Single(u => u.ID = userid);
         user.Report = newReport;
         context.SaveChanges();
    }
}

For an existing report:

public bool ChangeUserReport(int userid, Report existingReport)
{
    using (MyEntities context = new MyEntities())
    {
         context.Reports.Attach(existingReport);
         var user = context.Users.Single(u => u.ID = userid);
         user.Report = existingReport;
         context.SaveChanges();
    }
}

This is a sample how your model should look like. Double click on the association line to open the dialog. You can see that the Person and PersonID properties are the same. If you create your model like this, VS should generate the correct SQL. enter image description here

Upvotes: 1

Related Questions