Entity Save method, Context.SaveChanges correct usage

2 posts, 0 answers
  1. Shaun
    Shaun avatar
    1 posts
    Member since:
    Dec 2012

    Posted 18 Aug 2013 Link to this post

    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
  2. Damyan Bogoev
    Admin
    Damyan Bogoev avatar
    581 posts

    Posted 22 Aug 2013 Link to this post

    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.
  3. DevCraft banner
Back to Top