2017-07-31 67 views
0

当您想要将现有的子项添加到新的父项(1对1或1-n关系)时,首先使用代码,在Parent的Child和ChileId和EF自动映射该id给孩子。 有没有办法在多对多的关系上做同样的事情?实体框架通过多对多关系将现有的子项添加到新的父项

Parent 
{ 
    int ChildId {get;set;} 
    aClass Child {get;set;} 
} 

体系结构数据: 实体框架,第一代码。 后端webapi/restfull断开连接UI将ParentData映射到ParentEntity子集合将会像“countires”一样,所以我不想添加新的,但只是将许多countires关联到父级。用户界面上有一个多选下拉列表,因此您可以选中/取消选中这些国家/地区。

例如

家长与美国的关系,英国

然后在UI也有人检查ESP 3将与父

+0

[检查这一个](http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx) – Munzer

+0

关于下面的评论我的答案:你的问题没有包含足够的细节来帮助您解决多层架构问题。如果您不仅需要通用示例解决方案,还需要提供有关特定案例的更多详细信息。 – grek40

+0

完成后,我添加了更多信息。 Thx –

回答

0
using (var context = new YourContext()) 
{ 
    var mathClass= new Class { Name = "Math" }; 
    Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice"); 
    Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob"); 
    mathClass.Students.Add(student1); 
    mathClass.Students.Add(student2); 

    context.AddToClasses(mathClass); 
    context.SaveChanges(); 
} 

可能是这可以帮助你。

+0

'AddToClasses'看起来更像EF4的东西......你应该考虑将EF6或更新作为当前问题的默认值。 – grek40

+0

@ grek40你有没有在我的代码context.Math.Add(mathClass) –

+0

尝试像 这样的事我没有尝试过一件事,但我没有看到'context.Math.Add(mathClass)'在你的代码中,所以我不明白你的意思。 – grek40

1

在多对多中,使用ID代替整个对象并不容易。

考虑以下几点:

class Parent 
{ 
    public Parent() 
    { 
     Children = new List<Child>(); 
    } 
    public int Id {get;set;} 
    public ICollection<Child> Children { get; set; } 
} 
class Child 
{ 
    public Child() 
    { 
     Parents = new List<Parent>(); 
    } 
    public int Id {get;set;} 
    public ICollection<Parent> Parents { get; set; } 
} 

如果现有的孩子不加载(而不是想被预加载),您可以将ID为子条目只有建立的关系:

int existingChildId; // some value 
var childPlaceholder = new Child { Id = existingChildId }; 

db.Children.Attach(childPlaceholder); 

var newParent = new Parent(); 
newParent.Children.Add(childPlaceholder); 
db.Parents.Add(newParent); 

db.SaveChanges(); 

如果你不知道孩子是否已经装载的背景下,你仍然要避免数据库查询来加载它做,检查local条目:

int existingChildId; // some value 
var childPlaceholder = db.Children.Local.FirstOrDefault(x => x.Id == existingChildId) ?? 
    db.Children.Attach(new Child { Id = existingChildId }); 

// placeholder is ready to use 
+0

好吧,这似乎是我需要的方式......但我得到“{”保存或接受更改失败,因为'Model.Domain.DropDowns.Competitor'类型的多个实体具有相同的主键值。确保显式设置的主键值是唯一的。确保数据库生成的主键在数据库和实体框架模型中配置正确。使用实体设计器进行数据库优先/模型优先配置。使用'HasDatabaseGeneratedOption \ fluent API'或'DatabaseGeneratedAttribute'进行代码优先配置。“” –

+0

注意注释*“如果现有子代未加载”* ...否则,您需要使用已加载的子代条目。编辑考虑这种情况 – grek40

+0

我已经在集合中的孩子,并且它的状态被添加,并且当我尝试到该状态时更改失败 –

相关问题