使用EF6处理包含连接表的插入 [英] Handling inserts that include a junction table using EF6
问题描述
我正在设计一个表单,允许用户将基于结构的设计记录添加到数据库中。作为规范的一部分,用户希望能够从下拉列表中选择多个选项。在数据库中,我创建了设计表和一个查找表来存储选项。由于这是一对多的关系,因此我创建了一个联结表。
I'm designing a form that allows the user to add a design record based on a structure to a database. As part of the spec the users want to be able to choose multiple options from a dropdown. In my database I've created the design table and a lookup table to store the options. As this is a 1 to many to 1 relationship I've created a junction table.
Design table
-------------
designid,
option
Option table
------------
optionid,
optionname
DesignDesignOption table
------------------------
designid,
optionid
使用EF db first选项,我有2个模型称为design和option。 EF省略了联结表。
Using the EF db first option I have 2 models called design and option. EF has omitted the junction table.
从下拉列表中,我得到了一个ID后面的字符串数组,但该数组已被选择,但我不确定如何添加联接表的条目。是否需要查询数据库,根据ID从数据库中选择选项?我真的不知道该怎么做。
From the dropdown I'm getting a string array of id's back that have been chosen but I'm not sure how to go about adding the entry to the junction table. Do I have to query the db, select the options chosen from the database based on the id's? I really have no clue how to do this.
到目前为止,我的代码如下。到目前为止,我还没有添加处理联结表的代码:
My code so far is below. As yet I haven't added the code to handle the junction table:
public bool InsertDesign(Design design){
if (!Validate(design)) {
return false;
}
design.ModifiedDate = DateTime.Now;
design.ModifiedByFullName = base.GetUsersFullName();
design.ModifiedBy = base.GetUserLogin();
_context.Designs.Add(design);
_context.SaveChanges();
return true;
}
推荐答案
我想,你有选项ID列表,并且在 Design
模型中应该有 Options
导航属性。然后,您有两个选择:
I suppose that, you have list of OptionIds and there should be Options
navigation property at Design
model. Then you have two options:
如您所述,根据ID列表选择选项:
As you stated, select options according to list of Ids:
var optionIds = ...;
// Get options from database
List<Option> options = _context
.Options
.Where(m => optionIds.Contains(m.OptionId))
.ToList();
design.Options = options;
_context.Designs.Add(design);
_context.SaveChanges();
第二种选择:
如果不想从数据库中选择数据,则可以将添加选项的状态设置为不变;
Second option:
If you do not want to select data from database, then you can set state of added option to Unchanged;
using System.Data.Entity;
var optionIds = ...;
// Initialize options according to Ids
List<Option> optionList = new List<Option>();
optionIds.ForEach(m => optionList.Add(new Option { OptionId = m})));
// Set options of desing and add it to context
design.Options = optionList;
_context.Designs.Add(design);
// Set state of options to unchanged to not affect their data and save changes
optionList.ForEach(m => _context.Entry(m).State = EntityState.Unchanged);
_context.SaveChanges();
这篇关于使用EF6处理包含连接表的插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!