vendredi 22 janvier 2016

Universal Windows App 10 - EF7 SQLite One-to-many relationship

I'm new to developing UWA. I'm trying to develop an app that stores information on a local database.

I can store and get information without problem, but I can't find how to work with relationships.

I have:

public class ToDoItem
{
    public int ToDoItemId
    {
        get; set;
    }

    public int ToDoItemCategoryId
    {
        get; set;
    }

    public virtual ToDoItemCategory ToDoItemCategory
    {
        get; set;
    }

    [Required]
    public string Description
    {
        get; set;
    }
}

And:

public class ToDoItemCategory
{
    public int ToDoItemCategoryId
    {
        get; set;
    }

    public virtual ICollection<ToDoItem> ToDoItems
    {
        get; set;
    }

    [Required]
    public string Name
    {
        get; set;
    }
}

And, I'm saving the information this way:

       using (var db = new DatabaseContext())
       {
                var cat = db.ToDoItemCategories.Single(m => m.ToDoItemCategoryId == SelectedCategory.ToDoItemCategoryId);
                ToDoItem model = new ToDoItem() { Description = description, ToDoItemCategory = cat };
                db.ToDoItems.Add(model);
                db.SaveChanges();
       }

But ToDoItems don't get saved to the ToDoItemCategory ToDoItems list. Also, ToDoItemId is being auto-generated with negative ID's, I don't understand why.

I've also tried something similar to this:

    using (var db = new DatabaseContext())
    {
                var cat = db.ToDoItemCategories.Single(m => m.ToDoItemCategoryId == SelectedCategory.ToDoItemCategoryId);
                ToDoItem model = new ToDoItem() { Description = description, ToDoItemCategory = cat };
                db.ToDoItems.Add(model);
                cat.ToDoItems.Add(model);
                db.SaveChanges();
    }

But no luck. What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire