Saving a new object to the database with reference to an existing parent (foreign key)

NSouthManNSouthMan USMember ✭✭

In my Xamarin.Forms project there is a Category model which contains a list of Grades. The user must be able to select a Category and add a new Grade to it. However, I'm having trouble saving the Grade with a relationship to a parent Category.

Question: How do I add the Grade with reference to an existing parent Category?
My code is essentially doing the following to add a new Grade.

Category category = await cloudService.GetDefaultCategory();
Grade grade = new Grade() { Title = "Grade 1", Category = category };
await gradeTable.CreateItemAsync(Grade); // this is an IMobileServiceTable

When I attempt this, I get the following error.

The operation failed due to a conflict: 'Violation of PRIMARY KEY constraint 'PK_dbo.Categories'. Cannot insert duplicate key in object 'dbo.Categories'. The duplicate key value is (DA289023-09DC-45B8-B277-C3546E99F2DA).

Client models

public class Category : TableData
{
    public string Title { get; set; }
    public List<Grade> Grades { get; set; }
}
public class Grade : TableData
{
    public string Title { get; set; }
    public Category Category { get; set; }
}
public abstract class TableData
{        
    public string Id { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public byte[] Version { get; set; }
}

Server models

public class Category : EntityData
{
    public string Title { get; set; }
    public List<Grade> Grades { get; set; }
}
public class Grade : EntityData
{        
    public string Title { get; set; }
    public Category Category { get; set; }
}

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    It seems you want to insert an existed category to the database. I also didn't find a method called CreateItemAsync() in the IMobileServiceTable. Can you share the code about this method?

  • NSouthManNSouthMan USMember ✭✭

    Hi @LandLu, I should have clarified that CreateItemAsync() is an alias defined in an interface for the InsertAsync() method of IMobileServiceTable.

    I agree that it appears the back-end is interpreting my code as an attempt to insert an existing Category object to the database. Really, all I'm trying to do is insert a Grade object with a relationship to the existing Category object.

    I can think of 2 alternate approaches to try:

    1. Instead of inserting a new Grade object, Update the Category object to have an additional Grade child. But this seems like a weird implementation and this assumes EF is smart enough to interpret this and create the Grade object.
    2. Change my Grade class to have a CategoryId instead of a Category.

    Thoughts?

Sign In or Register to comment.