This question is coming from a frustration when using the Entity Framework and ASP.NET MVC, but I assume it's a general frustration across more frameworks and languages.
Lets say we have an object called Invoice
. The Invoice has a Recipient
. In my object model I have set it up like this:
[ForeignKey("Debtor")]
public int RecipientId { get; set; }
public virtual Recipient Recipient { get; set; }
In .NET, and assumably also other frameworks, that means when I have an Invoice object, I can lazyload the Recipient data.
If I save the Invoice object, it will also save the Recipient object in the Recipient database. That is in some cases very fine, but...
This is my problem
I also have a RecipientService
. Here I have some business logic before I store a Recipient. I will set a creation date, verify some fields are correct and set some other values. When I call my Create
method on my RecipientService
, this works perfectly.
But obviously, this code is completely skipped when I save my Invoice in database when using the ORM Entity Framework.
My question
What is the most common approach to solve this?
Is it to simply disallow saving objects with an actual object as a property, and just save it with the ID reference?
In my InvoiceService
I could easily say something like:
Recipient newRecipient = _recipientService.Create(recipient);
invoice.Recipient = null;
invoice.RecipientId = newRecipient.Id;
But is this really the best and most common approach?
I hope someone can help out here :-)