c# - Struggling with EF CodeFirst 1 to Many relationship -
i able tag movie 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 category not exist, created , dbcontext.categories.add(this) called inside category c'tor.
there no errors, new category not saved movie.categories.
i guessing because movie class belongs different context? unsure how structure this.
edit: if using database first approach, result movie_categories table has movie_id , category_id. why difficult?
i think want many-to-many relationship: 1 movie can have many categories , 1 category can belong many movies.
so category class needs public virtual icollection<movie> movies {get; set; } property.
your movie class this:
public class movie { public virtual icollection<category> categories { get; set; } public void addcategory(string name) { using (var dbcontext = new mydbcontext()) { // movie object dbcontext attached var movie = dbcontext.movies.singleordefault(m => m.name == name); // or match movie id instead of name var category = dbcontext.categories.singleordefault(x => x.name == name) ?? new category(name); movie.categories.add(category); dbcontext.savechanges(); } } } and category class:
public class category { public virtual icollection<movie>() movies { get; set; } public string name { get; set;} public category(string name) { name = name; } }
Comments
Post a Comment