silverlight - RIA Services: Entities Parent Child relationship -
in project using ria services, i've customer table , address table store address of each customer.
on page in silverlight, have customer data , when expand control, address data customer loaded.
when create new customer address, how save both separetely? address entity contains customerid. required field.
how can save address when customerid doesn't exist? , can not save customer first, because needs address.
what can do?
let me clarify something. because entities have navigational properties doesn't mean can't create them. perception have catch 22 "can't create 1 without other, can't create other without one" not quite how ef works.
there simple way of doing this. following example uses anonymous delegate (lambda exression) create customer first. once operation has returned server, delegate/lambda expression handles completed event , allows save address customer.
this model assumes have 1 many relationship between customer , address... aka: 1 customer can have many addresses. id field of customer foreign key in address (customerid).
private void savecustomerandaddress() { customercontext context = new customercontext(); customer c = new customer(); c.name = "daniel"; context.customers.add(c); context.submitchanges( submitchangescomplited => { //lambda expressions. executes when completed event fires //submitchanges. @ point customer entity created //will have id assigned context, can access //from within lambda expression block. address address = new address(); address.customerid = c.id; address.name = "home address"; address.state = "ca"; address.city = "san diego"; context.addresses.add(address); context.submitchanges(); }, null); }
if have meny-to-meny relationships between customers , addresses have bit more creative. opeartions follows: 1. save customer 2. save address 3. create record in joiner table customeraddress association.
note: using lambda expressions makes things bit easier because have ability access variables outside lambda expressions, long declared in same method. otherwise every operation have persist objects "state" if more 1 operations needed achieve want:
Comments
Post a Comment