开发者

EF navigation properties not loaded when hooking into get method from partial class

开发者 https://www.devze.com 2023-03-28 03:40 出处:网络
I\'m using the entity-framework with an asp.net mvc application and I\'m using the database-first approach. I customized the code generation from the edmx a little to be able to hook into the get meth

I'm using the entity-framework with an asp.net mvc application and I'm using the database-first approach. I customized the code generation from the edmx a little to be able to hook into the get method of the properties of my entities like this:

public partial class CA
{
    private string _PropX;
    partial void OnGetPropX(ref string value);
    public string PropX
    {
        get
        {
            string value= _PropX;
            this.OnGetPropX(ref value);
            return value;
        }
        set
        {
            this._PropX= value;
        }
    }

    public virtual CB B { get; set; }
}

As you can see, there is also a navigation property to CB. In my non-generated partial cl开发者_开发问答ass A, I hook into the get method for PropX to return a property on CB like this:

public partial class CA
{
    partial void OnGetPropX(ref string value)
    {
        if(String.IsNullOrEmpty(value))
            value= this.B.PropY;  // Error
    }
}

But it turns out this.B is always Null in the line marked with // Error. However, if I create a new property in my non-generated partial class CA, like the following, everything works just fine:

public string MyPropX
{
    get
    {
        return (String.IsNullOrEmpty(this.PropX) ? this.B.PropY: this.PropX);
    }
}

Could anyone please explain this behaviour to me and perhaps tell me how to get the first method to work? Thanks!


Random guess...but perhaps changing your property to be non virtual prevents EF from creating proxies properly...try doing public virtual string PropX instead...

0

精彩评论

暂无评论...
验证码 换一张
取 消