【发布时间】:2016-04-14 12:01:32
【问题描述】:
我使用GraphDiff 更新分离的对象图,并且在保存父对象及其子对象时出现上述异常。
模型和映射是:
public class Group
{
public int Id { get; set; }
public virtual ICollection<GroupUser> Users{ get; set; }
}
public class GroupUser
{
public int Id { get; set; }
public int GroupId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
public class GroupMap : EntityTypeConfiguration<Group>
{
public GroupMap()
{
this.ToTable("groups");
this.HasKey(t => t.Id).Property(t => t.Id).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasMany(t => t.Users)
.WithOptional()
.HasForeignKey(d => d.GroupId)
.WillCascadeOnDelete();
}
}
public class GroupUserMap : EntityTypeConfiguration<GroupUser>
{
public GroupUserMap ()
{
this.ToTable("groups_users");
this.HasKey(t => t.Id).Property(t => t.Id).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.GroupId).HasColumnName("group_id").IsRequired();
this.Property(t => t.UserId).HasColumnName("user_id").IsRequired();
this.HasRequired(t => t.User)
.WithMany()
.HasForeignKey(d => d.UserId)
.WillCascadeOnDelete(false);
}
}
对于插入和更新,我的存储库中有以下方法:
public override Group Update(Group entity)
{
if (entity.Users != null)
{
entity.Users.ToList()
.ForEach(x =>
{
x.GroupId = x.Id == 0 ? 0 : entity.Id;
x.UserId = x.User.Id;
});
}
return dbContext.UpdateGraph<Group>
(entity,
map => map.OwnedCollection(x => x.Users, with => with.AssociatedEntity(c => c.Users))
);
}
我执行以下操作:
- 添加新组,保存并重新加载
- 将用户添加到组,保存并重新加载
- 添加第二个用户,保存并重新加载
- 添加第三个用户,尝试保存 -> 抛出异常
在调试时,添加的用户实体的状态始终是分离的,对于新实体,GroupId 和 Id 都设置为 0。添加的前 2 个用户已成功保存。但是,在第三个中,抛出异常。
如果,我总是使用相同的方法进行保存,为什么它并不总是有效?是EF 还是GraphDiff 问题,有没有办法解决这个问题?
关于 SO 和其他地方的大多数问题和相关答案都涉及删除子实体的情况。在我的特定场景中不是这种情况。
【问题讨论】:
标签: c# entity-framework entity-framework-6 graphdiff