简体   繁体   中英

populate many-to-many relationship table using navigation properties in Entity Framework

I am learning Entity Framework in asp.net mvc application. I have 3 models -

AppModel, CategoryModel and App_CategoryModel (to specify many to many relationship between AppModel and CategoryModel). A snippet of this is:

public class CategoryModel
    {
        [Key]
        public int id { get; set; }
        public string Name {get; set; }
        public virtual ICollection<App_CategoryModel> mapping { get; set; }
    }

    public class AppModel
    {
        [Key]
        public int id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<App_CategoryModel> mapping { get; set; }
    }

    public class App_CategoryModel
    {
        [Key]
        public int id {get; set;}

        public int AppId {get; set; }
        public int CategoryId {get; set; }

        public virtual AppModel App {get; set;}
        public virtual CategoryModel Category {get; set;}
    }

I was following 'Code-first' approach and the tables got created successfully. But, now I am stuck at how to populate and display this information. I have the following as input data: List<AppModel> List<CategoryModel> and Dictionary<"appname", List<CategoryModel>>

How do I move on from here so that I can update the mapping table?

Also, wanted to understand whether this is the correct approach to represent data. Since an App can have multiple categories - I expect the output as a collection of unique Apps along with a list of categories for each app, something like:

Dictionary<AppModel, List<CategoryModel>>

Edit: This is what I tried as per suggestion from smoksnes-

    List<CategoryModel> cat_list = new List<CategoryModel>();
    CategoryModel c1 = new CategoryModel();
    c1.Name = "string1";
    cat_list.Add(c1);

    CategoryModel c2 = new CategoryModel();
    c2.Name = "string2";
    cat_list.Add(c2);

    List<AppModel> app_list = new List<AppModel>();
    AppModel a1 = new AppModel();
    a1.Name = "app1";
    app_list.Add(a1);

    AppModel a2 = new AppModel();
    a2.Name = "app2";
    app_list.Add(a2);

    a1.mapping.Add(c1);
    a1.mapping.Add(c2);
    a2.mapping.Add(c1);
    a2.mapping.Add(c2);

    db.categories.AddRange(cat_list);
    db.apps.AddRange(app_list);

    db.SaveChanges();

After this, EF worked as expeted - 2 categories , 2 apps and 4 entries in mapping table.

Although this worked, but not sure who is stopping EF to create 4 entries for categories?

Just as Barry O´Kane mentioned in your comment there's no reason to keep the App_CategoryModel model. EF will manage this for you. You should only keep it if it contains any extra information regarding the relation between the two tables. But according to your example, there's no reason to keep it.

public class CategoryModel
{
    public CategoryModel()
    {
        AppModels = new List<AppModel>();
    }

    [Key]
    public int id { get; set; }
    public string Name {get; set; }
    public virtual ICollection<AppModel> AppModels { get; set; }
}

public class AppModel
{
    public AppModel()
    {
        // Not sure if this is actually needed anymore. But EF usually adds it.
        CategoryModels = new List<CategoryModel>();
    }

    [Key]
    public int id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<CategoryModel> CategoryModels { get; set; }
}

And regarding your question about representation, I don't think it's necessary. Since the AppModel already has the connected CategoryModel on it's model there's no reason for a Dictionary . You can store it in a List<AppModel> instead.

IList<AppModel> myApps = context.AppModels.ToList();

foreach (var myApp in myApps)
{
    Console.Writeline("App {0} has the following categories:", myApp.id);
    foreach (var category in myApp.CategoryModels)
    {
        Console.Writeline(category.Name);
    }
}

And when you want to add a category to an app:

// I don't know how you create your Context, so below it's just called context.
var newCategoryModel = new CategoryModel
{
    Name = "SO is awesome!"
};
var appModel = context.AppModels.FirstOrDefault(x => x.id == 1);
appModel.CategoryModels.Add(newCategoryModel); // EF will automatically set foreign keys for you...
context.SaveChanges();

And if you want to make sure that no category is added twice:

public void AddCategory(int appId, string categoryName)
{
    using(var context = new DbContext())
    {
        var category = context.CategoryModels.FirstOrDefault(x => x.Name == categoryName);
        if(category == null)
        {
            // Only create new CategoryModel if it doesn't exist.
            category = new CategoryModel
            {
                Name = categoryName
            };
        }
        var appModel = new AppModel
        {
            id = appId
        };
        // Attach to save on db-trip
        context.AppModels.Attach(appModel);

        //TODO: Possibly check if this particular appModel already has this category?
        appModel.CategoryModels.Add(category);
        context.SaveChanges();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM