I'm just discovering LINQ and finding it great. One problem thoush is that I have to copy a lot of fields during an update in a 3-tier (layer) application. The algorithm I used shows a typical LINQ update of a class.
- I receive the object
FromPresentation
from the presentation layer. - I use LINQ to get the object with the same ID from the database.
- I change a lot of fields
- Save the changes.
And the corresponding code:
using (var ctx = new AppDataDataContext())
{
var OBJ =
(from Usu in ctx.usuarios
where Usu.ID == FromPresentation.ID
select Usu).SingleOrDefault();
if (OBJ != null)
{
OBJ.Nome = FromPresentation.Nome;
OBJ.NomeCurto = FromPresentation.NomeCurto;
OBJ.Login = FromPresentation.Login;
OBJ.Senha = FromPresentation.Senha;
OBJ.SuperUsuario = FromPresentation.SuperUsuario;
OBJ.Ativo = FromPresentation.Ativo;
// a lot more fields
ctx.SubmitChanges();
return OBJ.ID;
}
}
The problem is that I have a lot of fields. I even tried using reflection (using this question for guidance) to copy the fields but LINQ is not notified of the changes so it doesn't save anything.
How can I use reflection to copy values to a LINQ object so it can be updated in the database?