How to get EF POCOs from System.Data.Entities.Dyna

2019-06-09 19:45发布

问题:

My question is the same as this one

However, I don't really see a solution there. Lets say I have a simple model with two POCOs, Country and State.

public class Country
{
    public string Code { get; set; }
    public string Name { get; set; }
}
public class State 
{
    public string Code { get; set; }
    public string Name { get; set; }

    public virtual Country Country { get; set; }
}

When I use the repository to .GetStateByCode(myCode), it retrieves a dynamic proxy object. I want to send that over the wire using a WCF service to my client. The dynamic proxy is not a know type so it fails.

Here are my alternatives. I can set ProxyCreationEnabled to false on the context and then my .GetStateByCode(myCode) gives me a POCO which is great. However, the navigation property in the POCO to Country is then NULL (not great).

Should I new up a state POCO and manually populate and return that from the dynamic proxy that is returned from the repository? Should I try to use AutoMapper to map the dynamic proxy objects to POCOs? Is there something I'm totally missing here?

回答1:

I think the answer from Ladislav Mrnka is clear. The Warnings Still apply. Even with this idea below. Becareful what gets picked Up. He just didnt include , if you want to proceed how to easily get data from Object a to object B. That is question at hand really.

Sample solution

See nuget package ValueInjecter (not the only tool that can do this... but very easy to use) it allows easy copying of One object to another especially with the same properties and types. ( remember the lazy loading / navigation implications).

So vanilla option is :

 var PocoObject = new Poco();
 PocoObject.InjectFrom(DynamicProxy); // copy contents of DynamicProxy to PocoObject

but check the default behaviour and consider a custom rule

     var PocoObject = new Poco();
     PocoObject.InjectFrom<CopyRule>(DynamicProxy);

 public class CopyRule : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            bool usePropertry;   // return if the property it be included in inject process
            usePropertry = c.SourceProp.Name == "Id";  // just an example
            //or
            // usePropertry = c.SourceProp.Type... == "???"
            return usePropertry;
        }
    }