entity framework - WCF + EF return object with FK -
i facing following issue: have productorder class has productid foreign key product class. when invoke following method:
public ienumerable<productorder> getorders() { return oddzialdb.productorders; }
orders associated product can write this:
oddzialdb.productorders.first().product.name;
but when reaches client turns out there no association product null (only productid included). in dbcontext have set
base.configuration.proxycreationenabled = false; base.configuration.lazyloadingenabled = false;
on wcf service side auto-generated ef productorder class looks follows:
public partial class productorder { public int id { get; set; } public nullable<int> productid { get; set; } public int quantity { get; set; } public virtual product product { get; set; } }
what happens looses connections tables associated foreign keys?
make relationship virtual in example:
public class productorder { public int id { get; set; } public virtual product product { get; set; } public int productid { get; set; } }
by turning relationship virtual
, entity framework generate proxy of productorder
class contain reference of product
.
to make sure work, product
has contain reference productorder
:
public class product { public int id { get; set; } public string name { get; set; } public virtual icollection<productorder> productorders { get; set; } }
set these variables true on dbcontext
:
configuration.lazyloadingenabled = true; configuration.proxycreationenabled = true;
on wcf application, add following class, allow proxy serialization:
public class applydatacontractresolverattribute : attribute, ioperationbehavior { public applydatacontractresolverattribute() { } public void addbindingparameters(operationdescription description, bindingparametercollection parameters) { } public void applyclientbehavior(operationdescription description, system.servicemodel.dispatcher.clientoperation proxy) { datacontractserializeroperationbehavior datacontractserializeroperationbehavior = description.behaviors.find<datacontractserializeroperationbehavior>(); datacontractserializeroperationbehavior.datacontractresolver = new proxydatacontractresolver(); } public void applydispatchbehavior(operationdescription description, system.servicemodel.dispatcher.dispatchoperation dispatch) { datacontractserializeroperationbehavior datacontractserializeroperationbehavior = description.behaviors.find<datacontractserializeroperationbehavior>(); datacontractserializeroperationbehavior.datacontractresolver = new proxydatacontractresolver(); } public void validate(operationdescription description) { // validation. } }
then on servicecontract
interfaces add dataannotation
[applydatacontractresolver]
right among other annotations such [operationcontract]
, above method signature returns entity:
[operationcontract] [applydatacontractresolver] [faultcontract(typeof(atcwcfentrynotfoundexception))] case getsinglebycasenumber(int number);
Comments
Post a Comment