I would like to be able to subclass automatically generated LINQ to SQL Data Classes and save changes to said objects.
For example, if I have a table Client in my database, I can create ClientBO that extends class Client, and adds behaviors like GenerateInvoice() or whatever. Everything works fine until I want to update values in a subclass or insert a new record. Such changes are (predictably?) discarded. Is there something I’m missing, or am I violating a LINQ to SQL or OO principle by creating these subclasses in the first place?
Following are simplified examples of my code:
public class ClientBO : Client
{
public ClientBO( Client source ) : base()
{
FirstName = source.FirstName;
Lastname = source.LastName;
// ... etc ...
}
}
List<ClientBO> clientList =
( from client in DatabaseContext.Clients select new ClientBO( client ) ).ToList();
clientList[ someIndex ].SomeField = NewValue;
MyDatabaseContext.SubmitChanges();
The problem is that the object you are changing is no longer the same object as gotten from the data store.
The DataContext tracks changes to all objects it have attached. But as you never change the “source”-object as you refer it to, the data context is never notified of the change
I would suggest you to make your
ClientBOa partial class of theClientinstead (of course, renaming it to Client). All Linq-To-Sql classes are generated as partial and thus you can easily extend them this wayLike this: