代码之家  ›  专栏  ›  技术社区  ›  cllpse

Linq to SQL-插入具有关系的实体

  •  0
  • cllpse  · 技术社区  · 14 年前

    考虑下表(Visual Studio中DBML文件编辑器的屏幕截图):

    http://roosteronacid.com/dbml.png

    这个 入职员工与员工之间的关系 表是多对多表,链接 n 只需一份食谱。


    您如何插入以下配方…:

    Recipe { Name = "Dough" }
    

    含以下成分……:

    Ingredient { Name = "water", Unit = "cups", Amount = 2.0 },
    Ingredient { Name = "flour", Unit = "cups", Amount = 6.0 },
    Ingredient { Name = "salt", Unit = "teaspoon", Amount = 2.0 }
    

    …进入数据库?

    2 回复  |  直到 14 年前
        1
  •  1
  •   cllpse    14 年前

    创建配方和成分,然后为每个成分创建与该成分相关联的关系。将这些关系中的每一个添加到配方中,并将配方插入数据库。

    var recipe = new Recipe { Name = "Dough" };
    
    var ingredients = new []
    { 
       new Ingredient { Name = "water", Unit = "cups", Amount = 2.0 }, 
       new Ingredient { Name = "flour", Unit = "cups", Amount = 6.0 }, 
       new Ingredient { Name = "salt", Unit = "teaspoon", Amount = 2.0 }
    };
    
    foreach (var ingredient in ingredients)
    {
       var relation = new IngredientsRecipesRelations();
    
       relation.Ingredient = ingredient;
    
       recipe.IngredientsRecipesRelations.Add(relation);
    }
    
    DataContext.Recipes.InsertOnSubmit(recipe);
    DataContext.SubmitChanges();
    

    注意,您可以添加一个带有方法的部分类实现,以从使用它的类中隐藏此行为。您希望使关联在内部范围内,然后公开一些公共方法来添加/删除与内部关联协同工作的成分,如我上面所演示的。

        2
  •  0
  •   Pharabus    14 年前

    阿扎姆沙普是正确的,因为它不支持多对多,然而这 link 通过某种方式来展示它是如何完成的,本质上,您将手工制作一些代码。