views:

61

answers:

1

it seems if i use an custom class as base of an entity,the ObjectContext.CreateObjectSet will fail with stackoverflow exception

code is:

// This is generated by EF4 and i modify it to my custom class
public partial class EntityA : GClass<EntityA>
{
    ......
}

public partial class TestEntities : ObjectContext
{
    public ObjectSet<EntityA> EntityAs
    {
        get
        {
            if ((_EntityAs == null))
            {
                // here will throw stackoverflow exception
                _EntityAs = base.CreateObjectSet<EntityA>("EntityAs");
            }
            return _EntityAs;
        }
    }
    private ObjectSet<EntityA> _EntityAs;
}


// This is custom class
public partial class EntityA
{
}

// This is my custom base class
public class GClass<T> : EntityObject where T : class
{
    public virtual string GetStr()
    {
        return "GClass";
    }
}
A: 

I recommend creating an interface for your entity objects instead of changing the base class. Generated code should not be modified.

Update: Due to unexplained downvotes, I'm adding the code below, which spells out precisely what I mean:

// Generated by EF4
public partial class EntityA : EntityObject
{
    ...
}

// Interface defined in another file
public interface IGClass<T> where T : IGClass<T>
{
    string GetStr();
}

// Automatically generated by T4 template
public partial class EntityA : IGClass<EntityA>
{
    public virtual string GetStr()
    {
        return "GClass";
    }
}

The resulting code does use CRGP, but does so via an interface instead of a base class.

More info on T4 templates is here.

Stephen Cleary
the generated code could be modified via a code generator.I need to put the common methods to the base class.
vsico.ou
I still recommend creating an interface. The implementations can be generated into the partial class (in another file). Is there any reason that wouldn't work?
Stephen Cleary
if use interface,i will need to implement things to every class,what i need is a base class to handle common process.
vsico.ou
As mentioned in my answer, a `T4` template would make it easy to implement all these functions in the derived classes.
Stephen Cleary
yes,this should be one of the solutions,but i think it's a little hard to maintain,and less code-reuse.another way is use POCO instead of inherit from EntityObject.another thread i opened in MSDN:http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/c13a60cf-6121-47a4-b4f8-40cb8d6f109a
vsico.ou