4

In entity framework you have to write a lot of code for saving or updating a single entity:

 using (DataContext context = new DataContext())
    {
        context.Task.Attach(task);
        if (task.ID == 0)
        {
             context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Added);
        }
        else
        {
             context.ApplyOriginalValues(task.GetType().Name, task);
         }
          context.SaveChanges();
     }

in hibernate it is just saveOrUpdate()

This is not about being lazy, it is about making it short and clean.

SexyMF
  • 10,657
  • 33
  • 102
  • 206

1 Answers1

4

There is no equivalent. You really have to write it like:

using (DataContext context = new DataContext())
{
    context.Task.Attach(task);
    if (task.ID == 0)
    {
         context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Added);
    }
    else
    {
         context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Modified);
    }

    context.SaveChanges();
 }
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Can you think of a way to wrap it? (for relations support as well) thanks – SexyMF Sep 26 '11 at 09:09
  • For relations it is even worse: http://stackoverflow.com/questions/3635071/update-relationships-when-saving-changes-of-ef4-poco-objects/3635326#3635326 and don't think that it can be easily wrapped. – Ladislav Mrnka Sep 26 '11 at 09:18
  • I am in the beginning of my project, can you recommend on something (other ORM) more elegant? Thanks – SexyMF Sep 26 '11 at 09:20
  • You mentioned Hibernate so you can use NHibernate for .NET if you don't like EF. – Ladislav Mrnka Sep 26 '11 at 09:22
  • Is it more elegant? I remember from java that it is better, how is it in .NET? or why not LINQ? thanks – SexyMF Sep 26 '11 at 09:26
  • 1
    If you used Hibernate in Java you will like NHibernate. Linq-to-Sql is like one-to-one mapping of tables to classes with ability to query them with Linq. It has it pros and cons but you will again have to do a lot of plumbing. – Ladislav Mrnka Sep 26 '11 at 09:32
  • Can you help with that? http://stackoverflow.com/questions/7553095/entity-framework-object-wont-be-saved (-: – SexyMF Sep 26 '11 at 09:38