0

My question is related to this issue. I have a POCO class with virtual navigation property from the child to the parent. The parent has a collection of children.

public class Parent
{
    public virtual List<Child> Children { get; set; }
}

public class Child
{
    public string ParentID { get; set; }

    [XmlIgnore]
    [ForeignKey("ParentID")]
    public virtual Parent Parent { get; set; }
}

Now... you guessed it - I try to serialize the parent that comes from EF(i.e. the proxy) with the XmlSerializer. It first complains about all unkown types(the dynamically generated classes) which I handle somehow. But then it exepts with a 'circular reference' exception.

The reason after some investigation turns out to be that the XmlIgnore attribute is not discoverable via reflection on the proxy object's Parent property.

    Type.GetType("System.Data.Entity.DynamicProxies.Child_2C9351FD5E156D94E5BF2C68DABFC2A956181C99A0C2E4E6B592E6373D8645ED, EntityFrameworkDynamicProxies-Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
.GetProperty("Parent").GetCustomAttributes(typeof(XmlIgnoreAttribute), true) <-- returns 'None'

The proxy object's type base type is my Child class. The XmlIgnoreAttribute doesn't set the Inherited flag, and the default is true, so this should work. What is happening?

Is the proxy object lying about it's base type?

How can I workaround this issue without writing 'manual' xml serialization(I need to use the XmlSerializer).

UPDATE: It turns out that the XMLSerializer doesn't respect the 'inheritness' of the attributes which seems wrong. Is that a bug or is it by design?

4

1 回答 1

0

根据msdn 文章(备注部分):

'此方法忽略属性和事件的继承参数。要在继承链中搜索属性和事件的属性,请使用 Attribute.GetCustomAttributes 方法的适当重载。

所以这不必对代理做任何事情。看看这个例子:

public class Test
{
    [XmlIgnore]
    public virtual int Property { get; set; }
}

public class Derived : Test
{
    public override int Property { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(
            typeof(Derived)
           .GetProperty("Property")
           .GetCustomAttributes(typeof(XmlIgnoreAttribute), true)
           .Count());

        Console.WriteLine(
           Attribute.GetCustomAttributes(
               typeof(Derived)
              .GetProperty("Property"), true)
              .Count());
    }
}

结果:

0
1
Press any key to continue . . .
于 2013-01-18T06:49:43.320 回答