It\'s well known that you cannot set foreign key IDs directly in Linq to SQL if the entities have already been loaded. You can however look up the entity by it\'s foreign k
There are two main schools of thought on this:
Put the logic in the DataContext
(partial class, or actual class if you code your DataContext
by hand). The rationale behind this is that your DataContext
already knows about all of your different entities, so this isn't creating any additional coupling and isn't leading to class bloat.
The disadvantage, of course, is that if you have a few hundred of these API methods (and you probably will, eventually) then your DataContext
will quickly start turning into a ball of mud, filled with every random query API any programmer decides to throw in. You can try to clean this up by separating related functions into different instances of the same partial DataContext
class, but that's really only a cosmetic improvement.
Put the logic in a repository class, i.e. an AppointmentRepository
. Two advantages to this approach are (a) the ability to use dependency injection on the repository and an IoC framework, in case you decide to change your data model, and (b) the fact that you're sticking to the Single Responsibility Principle - it actually makes sense for the method to be where it is.
The main disadvantages to putting these in repositories are: (a) They may be duplicating very similar logic that's already in your DataContext
as Stored Procedures; (b) they have a way of creating headaches when it comes to transaction management (if you also use them to save); and (c) when you start to have a lot of custom queries that return specially-tailored DTOs for specific operations or reports, you're left with the two crummy choices of either creating one repository for each and every DTO, or creating one master "utility" repository for all the DTOs or some loosely-related group of them. Both end up being a rather poor design.
Those are the tradeoffs; only you can decide which is better for your own purposes.
I would definitely advise against the extension-method approach, as extension methods are difficult to discover (you can't just type the method and have Intellisense pick up the relevant reference), and they're also simply not necessary when you have the ability to directly modify or extend (via partials) the original class.
I'd also advise against extending the Appointment
class; one of the reasons we use tools like Linq To SQL is so we can deal with POCO entities that don't need to know anything about where they came from. For this reason I personally am very much against the coupling of entity classes to their DataContext
- the dependency should be only one-way.