Base solution for your next web application
Open Closed

Using a GUID as a primary key #215


User avatar
0
ghua created

Hi I want to use the GUID the master keys, however, inserted in the EfRepositoryBase method if (entity. IsTransient()) { Context.SaveChanges(); } If my ID assignment, then inserted into the database ID (GUID) is the default value, ID is fixed is the default value, if I was ID assignment, then this method returns false, does not implement Context.SaveChanges (), the data cannot be inserted into the database, I'm very upset, did I miss anything? Looking forward to your reply


2 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    I checked EfRepositoryBase, there are InsertAndGetId and InsertOrUpdateAndGetId methods like you said. But there is no problem. Example:

    public override TPrimaryKey InsertAndGetId(TEntity entity)
            {
                entity = Insert(entity);
    
                if (entity.IsTransient())
                {
                    Context.SaveChanges();
                }
    
                return entity.Id;
            }
    

    This SaveChanges is called just to get Id of the new entity. It's needed if Id is autoincrement or somehow determined by database. If you set Id before calling this method, it will not call SaveChanges. This is also normal because we have an Id and no need to save it now. It will be saved when UOW is completed. Your entity is inserted to database when your UOW completed. So, what's your problem here?

    If you really want to insert entity to database in middle of a UOW, you can then call IUnitOfWorkManager.Current.SaveChanges(); See documentation: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work">http://www.aspnetboilerplate.com/Pages/ ... it-Of-Work</a>

  • User Avatar
    0
    ghua created

    This solved my confusion,Thank you so much. :D