This is a migrated thread and some comments may be shown as answers.

Entity Save method, Context.SaveChanges correct usage

1 Answer 109 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Shaun
Top achievements
Rank 1
Shaun asked on 18 Aug 2013, 05:24 AM
Hi there, I have a two varieties of Save methods


public void Save()
{
    if (Id > 0)
    {
        using (var dbContext = OpenAccessContextBase.GetContext(this))
        {
            dbContext.Add(this);
            dbContext.SaveChanges();
        }
    }
    else
    {
        using (var dbContext = new SystemEntityModel())
        {
            dbContext.Add(this);
            dbContext.SaveChanges();
        }
    }
}

And

public void Save()
{
    using (var cachedContext = OpenAccessContextBase.GetContext(this))
    {
        if (cachedContext != null)
        {
            cachedContext.Add(this);
            cachedContext.SaveChanges();
        }
        else
        {
            using (var dbContext = new SystemEntityModel())
            {
                dbContext.Add(this);
                dbContext.SaveChanges();
            }
        }
    }
}

This is on a web-based application, is there a more elegant way to do this? I'm sure I've even had exceptions on the first block, when trying to use OpenAccess.GetContext().

The object was retrieved using 

new SystemEntityModel().GetAll<MyEntity>();


What is the correct way to always ensure dbContext.Add/dbContext.SaveChanges() doesn't fail?

Thanks

1 Answer, 1 is accepted

Sort by
0
Damyan Bogoev
Telerik team
answered on 22 Aug 2013, 09:40 AM
Hi Shaun,

The OpenAccessContextBase.GetContext(object instance) method returns the context responsible for the managing of the passed object. If the provided instance is new for instance, the method will return null and you need to instantiate a new context instance. 

If the object is already persisted (saved) in the database, there is not need to use the OpenAccessContext.Add(object instance) method to start managing by the obtained context.

Hope that helps.

Regards,
Damyan Bogoev
Telerik
OpenAccess ORM Q2 2013 brings you a more powerful code generation and a unique Bulk Operations support with LINQ syntax. Check out the list of new functionality and improvements shipped with this release.
Tags
Development (API, general questions)
Asked by
Shaun
Top achievements
Rank 1
Answers by
Damyan Bogoev
Telerik team
Share this question
or