我得到这个错误时,我GetById()在一个实体,然后设置子实体的集合到我的新列表,来自MVC视图。

操作失败 关系是无法改变的 因为一个或多个外键 Properties是非空的。当一个 关系发生了变化 相关外键属性设置为 空值。如果外键是 不支持空值,新建 关系必须被定义 必须分配外键属性 另一个非空值或 必须删除不相关的对象。

我不太理解这句话:

这种关系无法改变 因为一个或多个外键 Properties是非空的。

我为什么要改变两个实体之间的关系?它应该在整个应用程序的生命周期内保持不变。

发生异常的代码只是简单地将集合中修改过的子类分配给现有的父类。这将有望满足取消子类,增加新的和修改。我本以为实体框架处理这个。

代码行可以提炼为:

var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();

当前回答

我不知道为什么其他两个答案这么受欢迎!

我相信您认为ORM框架应该处理它是正确的——毕竟,这是它承诺交付的。否则,您的域模型就会被持久性问题所破坏。如果你正确地设置了级联设置,NHibernate就能很好地管理它。在实体框架中也有可能,他们只是希望你在建立数据库模型时遵循更好的标准,特别是当他们不得不推断应该做什么级联时:

您必须使用“识别关系”来正确地定义父-子关系。

如果你这样做,实体框架知道子对象是由父对象标识的,因此它必须是一个“级联删除孤儿”的情况。

除了上面的,你可能需要(从NHibernate的经验)

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

而不是完全替换列表。

更新

@Slauma的评论提醒我,分离实体是整体问题的另一部分。为了解决这个问题,您可以采用使用自定义模型绑定器的方法,通过尝试从上下文加载模型来构造模型。这篇博客文章展示了我的意思。

其他回答

我在几个小时前遇到过这个问题,并尝试了所有方法,但在我的情况下,解决方案与上面列出的不同。

如果你使用已经从数据库检索实体,并试图修改它的孩子的错误将发生,但如果你从数据库获得实体的新副本,不应该有任何问题。 不要用这个:

 public void CheckUsersCount(CompanyProduct companyProduct) 
 {
     companyProduct.Name = "Test";
 }

用这个:

 public void CheckUsersCount(Guid companyProductId)
 {
      CompanyProduct companyProduct = CompanyProductManager.Get(companyProductId);
      companyProduct.Name = "Test";
 }

你必须手动清除ChildItems集合,并在其中添加新项目:

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

之后,您可以调用DeleteOrphans扩展方法,它将处理孤立的实体(它必须在DetectChanges和SaveChanges方法之间调用)。

public static class DbContextExtensions
{
    private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();

    public static void DeleteOrphans( this DbContext source )
    {
        var context = ((IObjectContextAdapter)source).ObjectContext;
        foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
        {
            var entityType = entry.EntitySet.ElementType as EntityType;
            if (entityType == null)
                continue;

            var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
            var props = entry.GetModifiedProperties().ToArray();
            foreach (var prop in props)
            {
                NavigationProperty navProp;
                if (!navPropMap.TryGetValue(prop, out navProp))
                    continue;

                var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
                var enumerator = related.GetEnumerator();
                if (enumerator.MoveNext() && enumerator.Current != null)
                    continue;

                entry.Delete();
                break;
            }
        }
    }

    private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
    {
        var result = type.NavigationProperties
            .Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            .Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
            .Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
            .Where(v => v.DependentProperties.Length == 1)
            .ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);

        return new ReadOnlyDictionary<string, NavigationProperty>(result);
    }
}

您之所以会遇到这种情况,是因为组合和聚合之间存在差异。

在复合中,创建父对象时创建子对象,销毁父对象时销毁子对象。所以它的生命周期是由父节点控制的。例:一篇博客文章及其评论。如果一个帖子被删除,它的评论也应该被删除。对一篇不存在的文章发表评论是没有意义的。订单和订单项目也是如此。

在聚合中,子对象可以不考虑父对象而存在。如果父对象被销毁,子对象仍然可以存在,因为以后它可能被添加到不同的父对象。例如:播放列表和该播放列表中的歌曲之间的关系。如果播放列表被删除,歌曲不应该被删除。它们可能被添加到不同的播放列表中。

实体框架区分聚合和组合关系的方式如下:

对于复合:它期望子对象有一个复合主键(ParentID, ChildID)。这是通过设计来实现的,因为孩子的id应该在他们父母的范围内。 对于聚合:它期望子对象中的外键属性为空。

So, the reason you're having this issue is because of how you've set your primary key in your child table. It should be composite, but it's not. So, Entity Framework sees this association as aggregation, which means, when you remove or clear the child objects, it's not going to delete the child records. It'll simply remove the association and sets the corresponding foreign key column to NULL (so those child records can later be associated with a different parent). Since your column does not allow NULL, you get the exception you mentioned.

解决方案:

1-如果你有强烈的理由不想使用复合键,你需要显式地删除子对象。这可以比之前建议的解决方案更简单:

context.Children.RemoveRange(parent.Children);

2-否则,通过在你的子表上设置正确的主键,你的代码看起来会更有意义:

parent.Children.Clear();

如果你正在使用自动绘图器,面临以下问题是一个很好的解决方案,它为我工作

https://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplusfailed

因为问题是我们正在映射空导航属性,我们实际上不需要在实体上更新它们,因为它们在契约上没有改变,我们需要在映射定义上忽略它们:

ForMember(dest => dest.RefundType, opt => opt.Ignore())

所以我的代码是这样的:

Mapper.CreateMap<MyDataContract, MyEntity>
ForMember(dest => dest.NavigationProperty1, opt => opt.Ignore())
ForMember(dest => dest.NavigationProperty2, opt => opt.Ignore())
.IgnoreAllNonExisting();

当我要删除我的记录时,我也遇到了同样的问题,因为这个问题的解决方案是,当你要删除你的记录时,你在删除头/主记录之前丢失了一些东西,你必须写代码在头/主记录之前删除它的细节,我希望你的问题会得到解决。