开发者

What is the equivalent for Hibenate.saveOrUpdate() in entity framework

开发者 https://www.devze.com 2023-04-08 15:00 出处:网络
In entity framework you have to write a lot of code for saving or updating a single entity: using (DataContext context = new DataContext())

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.


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();
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消