在插入新的父对象时,防止EF添加新的子对象而不是关联? [英] Prevent EF from adding new child objects instead of just association when inserting new parent object?
问题描述
我有以下内容:
public int CreateExercise(Exercise newExercise){
db。 Exercises.Add(newExercise);
db.SaveChanges();
return newExercise.ExerciseId;
}
运动如下:
public class Exercise {
public Exercise(){
Users = new Collection< User>();
}
[Key]
[必需]
public int ExerciseId {get;组; }
[StringLength(300,ErrorMessage =该值不能超过300个字符。)]
public string Title {get;组; }
public virtual ICollection< User>用户{get;组; }
}
当我创建一个新的练习时,有时预先存在的用户随身携带,Id包含。即使对于这些用户
指定的现有 UserId
,新的用户
条目被添加到这里。我只想添加关联,而不是新用户 - 我想象,EF很聪明,可以弄清楚这一点?我究竟做错了什么?
我只是想避免必须循环遍历所有附加到新练习的用户,在添加$ c $之前清除它们c> ing,确保它们存在,添加练习,然后添加每个用户,最后调用
SaveChanges
。
当连接的实体重新连接时,默认情况下它们处于添加状态。
public int CreateExercise(练习newExercise){
db.Exercises.Add(newExercise);
//将所有附加的用户设置为不变。
db.ChangeTracker.Entries< User>()。ToList()。ForEach(p => p.State = EntityState.Unchanged);
db.SaveChanges();
return newExercise.ExerciseId;
}
I have the following:
public int CreateExercise(Exercise newExercise) {
db.Exercises.Add(newExercise);
db.SaveChanges();
return newExercise.ExerciseId;
}
Where Exercise is the following:
public class Exercise {
public Exercise() {
Users = new Collection<User>();
}
[Key]
[Required]
public int ExerciseId { get; set; }
[StringLength(300, ErrorMessage = "The value cannot exceed 300 characters. ")]
public string Title { get; set; }
public virtual ICollection<User> Users{ get; set; }
}
When I create a new Exercise, sometimes pre-existing Users come with it, Id included. Even with an existing UserId
specified for these Users
, new User
entries are getting added here. I only want to add associations, not new users - I'd imagine EF is smart enough to figure this out? What am I doing wrong?
I'm just trying to avoid having to loop through all Users attached to a new Exercise, clearing them out before Add
ing, making sure they exist, adding the exercise, and then adding each individual user, finally calling SaveChanges
.
When disconnected entities are reattached they are in Added state by default.
You can change the state after attaching the exercise.
public int CreateExercise(Exercise newExercise) {
db.Exercises.Add(newExercise);
// set all attached users to unchanged.
db.ChangeTracker.Entries<User>().ToList().ForEach(p => p.State = EntityState.Unchanged);
db.SaveChanges();
return newExercise.ExerciseId;
}
这篇关于在插入新的父对象时,防止EF添加新的子对象而不是关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!