违反多重性约束(在XAF中,当未访问createdObject.ObjectSpace.ModifiedObjects.Count时。)

时间:2019-01-07 17:26:24

标签: entity-framework-6 xaf

问题摘要:

为什么通过引入以下代码行可以解决“违反多重性约束”的问题?

var numModifiedObjects =createdObject.ObjectSpace.ModifiedObjects.Count;

是否存在不需要进行任何设置的设置?

问题的背景以及解决方法:

在我的winforms xaf,EF6.2代码优先项目中,我具有以下自引用的业务对象。

[NavigationItem("Main")]
public class H2Category : IHCategory 
{
    public H2Category()
    {
        Children = new BindingList<H2Category>();
    }
    [Browsable(false)]
    public Int32 ID { get; protected set; }
    public String Name { get; set; }

    public H2Category Parent { get; set; }

    public virtual IList<H2Category> Children { get; set; }

    [NotMapped, Browsable(false), RuleFromBoolProperty("H2CategoryCircularReferences", DefaultContexts.Save, "Circular refrerence detected. To correct this error, set the Parent property to another value.", UsedProperties = "Parent")]
    public Boolean IsValid
    {
        get
        {
            H2Category currentObj = Parent;
            while (currentObj != null)
            {
                if (currentObj == this)
                {
                    return false;
                }
                currentObj = currentObj.Parent;
            }
            return true;
        }
    }
    IBindingList ITreeNode.Children => Children as IBindingList;

    ITreeNode IHCategory.Parent
    {
        get => Parent as IHCategory;
        set => Parent = value as H2Category;
    }
    ITreeNode ITreeNode.Parent => Parent as ITreeNode;
}

,在dbContext OnModelCreating中,我使用

   modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

   modelBuilder.Entity<H2Category>().HasMany(x => x.Children).WithOptional(x => x.Parent);

Parent_Id);

SQL Server对象资源管理器中的数据库看起来正确  the SQL Server Object Explorer

并且数据看起来正确。

data table

在XAF树视图中,当用户添加子记录时,我希望将新子项的父项设置为当前记录。

为此,我正在使用NewObjectViewController

public partial class H2CategoryController : ViewController
{
    private NewObjectViewController controller;
    public H2CategoryController()
    {
        InitializeComponent();
        TargetObjectType = typeof(H2Category);
    }
    protected override void OnActivated()
    {
        controller = Frame.GetController<NewObjectViewController>();
        controller.ObjectCreated += controller_ObjectCreated;
        base.OnActivated();
    }
    private void controller_ObjectCreated(object sender, ObjectCreatedEventArgs e)
    {
        var createdObject = e.CreatedObject as H2Category;
        var currentObject = View.CurrentObject as H2Category;
        // inspection here shows that currentObject and createdObject are different but they have the same proxy
        var s = $"created object Id is {createdObject.ID}  current object id is {currentObject.ID}";
        Console.WriteLine(s);

        var propertyCollectionSource = (View as ListView)?.CollectionSource as PropertyCollectionSource;
        if (!(propertyCollectionSource?.MasterObject is H2Category master)) return;
        createdObject.Parent = master;
        createdObject.Name = "t";
        master.Children.Add(createdObject);

        Console.WriteLine(master.ID);

    }

    protected override void OnDeactivated()
    {
        controller.ObjectCreated += controller_ObjectCreated;
        base.OnDeactivated();
    }
}

用户一开始输入新记录,就会出现以下错误

    Multiplicity constraint violated. The role 'H2Category_Children_Source' of the relationship 'SBD.GL.Module.BusinessObjects.H2Category_Children' has multiplicity 1 or 0..1.

    at System.Data.Entity.Core.Objects.EntityEntry.AddDetectedRelationship[T](Dictionary`2 relationships, T relatedObject, RelatedEnd relatedEnd)
    at System.Data.Entity.Core.Objects.EntityEntry.AddRelationshipDetectedByGraph(Dictionary`2 relationships, Object relatedObject, RelatedEnd relatedEndFrom, Boolean verifyForAdd)
    at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInRelationshipsOfSingleEntity()
   at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInNavigationProperties(IList`1 entries)
   at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges()
   at System.Data.Entity.Core.Objects.ObjectContext.DetectChanges()
   at DevExpress.ExpressApp.EF.EFObjectSpace.DetectChanges()
   at DevExpress.ExpressApp.EF.EFObjectSpace.GetModifiedObjects()
   at DevExpress.ExpressApp.EF.EFObjectSpace.get_ModifiedObjects()
   at DevExpress.ExpressApp.Win.SystemModule.CustomCollectModifiedObjectsEventArgs.CollectModifiedObjects(Boolean checkObjectSpaceIsModified)
   at DevExpress.ExpressApp.Win.SystemModule.LockController.GetModifiedObjects()
   at DevExpress.ExpressApp.Win.SystemModule.LockController.CheckLocking(LockController controller)
   at DevExpress.ExpressApp.Win.SystemModule.LockController.CheckLocking(Object obj)
   at DevExpress.ExpressApp.Win.SystemModule.LockController.ViewObjectSpace_ObjectChanged(Object sender, ObjectChangedEventArgs e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at DevExpress.ExpressApp.BaseObjectSpace.OnObjectChanged(ObjectChangedEventArgs args)
   at DevExpress.ExpressApp.EF.EFObjectSpace.SetModified(Object obj, ObjectChangedEventArgs args)
   at DevExpress.ExpressApp.BaseObjectSpace.SetModified(Object obj, IMemberInfo memberInfo)
   at DevExpress.ExpressApp.DetailView.Editor_ControlValueChanged(Object sender, EventArgs e)
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at DevExpress.ExpressApp.Editors.PropertyEditor.OnControlValueChanged()
   at DevExpress.ExpressApp.Win.Editors.DXPropertyEditor.Editor_EditValueChanged(Object sender, EventArgs e)
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at DevExpress.XtraEditors.Repository.RepositoryItem.RaiseEditValueChangedCore(EventArgs e)
   at DevExpress.XtraEditors.Repository.RepositoryItem.RaiseEditValueChanged(EventArgs e)
   at DevExpress.XtraEditors.BaseEdit.RaiseEditValueChanged()
   at DevExpress.XtraEditors.BaseEdit.OnEditValueChanged()
   at DevExpress.XtraEditors.TextEdit.OnEditValueChanged()
   at DevExpress.XtraEditors.BaseEdit.OnEditValueChanging(ChangingEventArgs e)
   at DevExpress.XtraEditors.TextEdit.OnEditValueChanging(ChangingEventArgs e)
   at DevExpress.XtraEditors.BaseEdit.set_EditValue(Object value)
   at DevExpress.XtraEditors.TextEdit.OnMaskBox_ValueChanged(Object sender, EventArgs e)
   at DevExpress.XtraEditors.Mask.MaskBox.RaiseEditTextChanged()
   at DevExpress.XtraEditors.Mask.MaskBox.MaskStrategy.SimpleStrategy.DoAfterTextChanged(EventArgs e)
   at DevExpress.XtraEditors.Mask.MaskBox.OnTextChanged(EventArgs e)
   at System.Windows.Forms.TextBoxBase.WmReflectCommand(Message& m)
   at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
   at System.Windows.Forms.TextBox.WndProc(Message& m)
   at DevExpress.XtraEditors.Mask.MaskBox.BaseWndProc(Message& m)
   at DevExpress.XtraEditors.Mask.MaskBox.MaskStrategy.SimpleStrategy.DoWndProc(Message& m)
   at DevExpress.XtraEditors.Mask.MaskBox.WndProc(Message& m)
   at DevExpress.XtraEditors.TextBoxMaskBox.WndProc(Message& msg)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

error message

我注意到设置父项时调试值看起来正确  debug values

但是对于所有H2Category对象具有相同的代理值感到困惑。

我已经询问过issue at Dev Express,但在这里也询问它与实体框架有关。

[更新-解决方法]

我将IObjectSpaceLink接口添加到业务对象。这会将ObjectSpace公开为业务对象的属性。

当我在controller_ObjectCreated方法中休息一下时,我能够看到ModifiedObjects属性显示错误

ModifiedObjects error

我发现,如果我将createdObject.ObjectSpace.ModifiedObjects.Count分配给变量,则不会发生此问题。

       private void controller_ObjectCreated(object sender, ObjectCreatedEventArgs e)
    {
        var createdObject = e.CreatedObject as H2Category;
        var numModifiedObjects =createdObject.ObjectSpace.ModifiedObjects.Count;

        var currentObject = View.CurrentObject as H2Category;
        var s = $"created object Id is {createdObject.ID}  current object id is {currentObject.ID}";

        var propertyCollectionSource = (View as ListView)?.CollectionSource as PropertyCollectionSource;
        if (!(propertyCollectionSource?.MasterObject is H2Category master)) return;

        var m = e.ObjectSpace.GetObject(master);

        createdObject.Parent = m;
        createdObject.Name = "t";
        m.Children.Add(createdObject);
        numModifiedObjects = createdObject.ObjectSpace.ModifiedObjects.Count;
        Console.WriteLine(master.ID);

    }

我尝试禁用代理创建,但没有帮助。

exception

1 个答案:

答案 0 :(得分:0)

来自Dev Express support answer

由于我的H2Category类中的错误,该关系在我的项目中无法正常工作。必须将Parent属性声明为虚拟。

此外,我的ICategoryController与内置TreeNodeController冲突。该控制器还订阅NewObjectViewController.ObjectCreated事件,并将新创建的ITreeNode对象与在源列表视图中选择的父节点链接。默认情况下,保存更改时链接对象。要在创建后立即链接新对象,请将NewObjectViewController.LinkNewObjectToParentImmediately属性设置为true