简体   繁体   English

使用Entity Framework中的导航属性填充多对多关系表

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

I am learning Entity Framework in asp.net mvc application. 我正在asp.net mvc应用程序中学习实体框架。 I have 3 models - 我有3个模型-

AppModel, CategoryModel and App_CategoryModel (to specify many to many relationship between AppModel and CategoryModel). AppModel,CategoryModel和App_CategoryModel(指定AppModel和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>> 我有以下输入数据: List<AppModel> List<CategoryModel>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- 编辑:这是我尝试根据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. 此后,EF发挥了作用-映射表中有2个类别,2个应用程序和4个条目。

Although this worked, but not sure who is stopping EF to create 4 entries for categories? 尽管这可行,但是不确定谁阻止EF为类别创建4个条目?

Just as Barry O´Kane mentioned in your comment there's no reason to keep the App_CategoryModel model. 正如Barry O´Kane在您的评论中提到的那样,没有理由保留App_CategoryModel模型。 EF will manage this for you. EF将为您管理。 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 . 由于AppModel的模型上已经具有连接的CategoryModel ,因此没有理由使用Dictionary You can store it in a List<AppModel> instead. 您可以将其存储在List<AppModel>

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架多对多关系导航属性和ID - Entity Framework many-to-many relationship navigation properties and ids 实体框架 - 查询多对多关系表 - Entity Framework - querying a many-to-many relationship table 实体框架使用单独的表映射多对多自我关系 - Entity Framework Mapping Many-to-Many Self Relationship with Separate Table html 表中的实体框架多对多关系 - Entity Framework many-to-many relationship in a html table Entity Framework 7 多对多(相交表)“跳过导航”问题 - Entity Framework 7 Many-To-Many (intersect table) "skip navigation" problem 如何使用Entity Framework仅使用一侧的导航属性创建多个多对多关系? - How to create multiple many-to-many relationships with only one-sided navigation properties using Entity Framework? 使用Entity Framework Core以多对多关系为数据库播种 - Seeding the database with a many-to-many relationship using Entity Framework Core 在Entity Framework Core中使用具有多对多关系的列表 - Using Lists with Many-to-Many relationship in Entity Framework Core 实体框架4-具有视图的多对多关系 - Entity Framework 4 - Many-To-Many Relationship with a view 实体框架中的多对多关系 - Many-to-many relationship in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM