【问题标题】:LINQ to SQL and Attaching Child ObjectsLINQ to SQL 和附加子对象
【发布时间】:2009-06-17 16:05:23
【问题描述】:

我正在编写一个类,它将(希望)允许通过 LINQ to SQL 层操作数据,而无需知道您正在使用哪些单个对象。到目前为止,它适用于级联选择和插入,但我很难更新。

这是我正在使用的保存方法:

if ((long)entity.GetType().GetProperty(GetPrimaryKeyName(entity)).GetValue(entity, null) == 0)
            {
                Context.GetTable(entity.GetType()).InsertOnSubmit(entity);
            }
            else
            {
                Context.GetTable(entity.GetType()).Attach(entity, true);
            }

            foreach (PropertyInfo property in entity.GetType().GetProperties())
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntitySet<>))
                {
                    IEnumerable children = (IEnumerable)property.GetValue(entity, null);
                    foreach (object child in children)
                    {
                        Save(child);
                    }
                }
            }

这一直有效,直到我有一个子对象作为更新的一部分。例如,如果我传入一个带有 Address 子对象的 Customer 对象,该对象需要更新而不是插入,一旦我附加 Customer 对象,我现在的 EntitySet 中有两个 Address 对象——从数据库中提取的一个,和新的。然后,当它尝试附加第一个地址子对象时,我得到一个异常“无法附加已经存在的实体”。

有什么想法吗?

【问题讨论】:

    标签: sql linq


    【解决方案1】:

    您可以在附加父实体之前附加子实体吗?这会阻止附加问题吗?

    只需使用反射获取所有EntityRef 对象,并将每个对象的Entity 属性附加到相应的表中。

    【讨论】:

    • 我最终这样做了,你是对的。从“自下而上”附加解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多