Saving an entity through Ria Services removes all many to many relationships in the database
When I save an entity in silverlight using Ria Services, all the many to man开发者_如何学JAVAy relationships that the entity has in the database are removed.
The entity the server receives has the same values in the properties except all the lists are blank. When nHiberante saves the entity, it erases all the many to many relationships.
Is there a way to prevent nHiberante from updating many to many relationships in certain situations? (I have the mappings for that property set to lazy load already)
Is there an attribute that I can add to the entity or property so it will play better with Ria?
I am using Silverlight 4 with Ria and nHiberante 3 alpha.
Are you using the [Composition] attribute on your collections?
With RIA, you have two options for handling collections on an object graph. If you use the [Composition] attribute, then those child objects are only accessible through the parent object. If you are not using the [Composition] attribute, then you need SEPARATE methods on your DomainService to handle the Insert/Update/Delete of those objects.
As an example: Here's a service method I have that saves changes to a Ticket object. The Ticket object has a collection of TicketAction items. Those items are declared with the [Composition] attribute:
[MetadataType(typeof (TicketMetadata))]
public partial class Ticket
{
internal sealed class TicketMetadata
{
[Key] public int TicketId;
[Required]
public DateTime IncidentDate;
[Include]
[Composition]
[Association("Ticket_TicketActions", "TicketId", "TicketId")]
public List<TicketAction> TicketActions;
}
}
The service method for updating these looks like this:
public void Update(Ticket ticket)
{
foreach (var ticketAction in ticket.TicketActions)
{
if (ticketAction.IsNew)
ticketAction.TicketId = ticket.TicketId;
}
_ticketDataSource.Update(ticket);
}
For new TicketActions added to the Ticket, we have to associate the Ticket.TicketId to the TicketAction.TicketId so that it will get saved. I am not using NHibernate (we're working ADO.NET against Oracle; don't ask), but the point isn't the tech; it's that you need to get the keys associated properly.
If you aren't using the [Composition] attribute in this type of scenario then you MUST have a separate Insert and Update method for the TicketAction objects as RIA will first call those methods and then call the TicketUpdate method.
Does that make sense?
A better practice is to use presentation models for your Silverlight (Sl) entities instead of using NHibernate entities directly on SL.
public void UpdateTicketSl(TicketSl ticketSl)
{
var ticket = _ticketDataSource.GetById(ticketSl.TicketId);
//update ticket entity (Nhibernate entity) using ticketSl (Presentation Model)
_ticketDataSource.Update(ticket);
}
精彩评论