I would like to be able to tag my Movie
with a Category
.
public class Movie
{
public virtual ObservableCollection<Category> Categories { get; set; }
public void AddCategory(string name)
{
using (var dbContext = new MyDbContext())
{
var category = dbContext.Categories.SingleOrDefault(x => x.Name == name) ?? new Category(name, dbContext);
Categories.Add(category);
dbContext.SaveChanges();
}
}
}
public class Category()
{
public Category(string name, DbContext dbContext)
{
Name = name;
dbContext.Categories.Add(this);
dbContext.SaveChanges();
}
}
If the category does not exist, it is created and dbContext.Categories.Add(this)
is called inside the Category
c'tor.
There are no errors, but the new Category
is not saved to my Movie.Categories
.
I am guessing it is because my Movie
class belongs to a different context? I am unsure how to structure this.
EDIT: If i was using a database first approach, this would result with a Movie_Categories
table that has a Movie_Id
and a Category_Id
. Why is this so difficult?