C#, entity framework, auto increment

前端 未结 5 1271
粉色の甜心
粉色の甜心 2020-12-02 23:07

I\'m learning Entity Framework under VC# 2010.

I have created a simple table for learning purposes, one of the fields is \"id\" type integer, identity set to true. I

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 23:40

    I had similar issues, which occurred in EF6 (did work in EF4 without transactions, EF 4 used implicit transactions with the right scope).

    Just creating a new entity and saving it did not help in my case (see the comments of the other answers, they had similar issues with using dc.SaveChanges() only to auto-update).

    Consider the following code (CustomerId is the primary key with auto-increment):

    public void UpdateCustomer(string strCustomerName, string strDescription)
    {
      using (var transaction = CreateTransactionScope())
      {
        MyCustomer tbl=null;
        Func selectByName=(i => i.CustomerName.Equals(strCustomerName));
        var doesRecordExistAlready = dc.MyCustomers.Any(selectByName); 
        if (doesRecordExistAlready) 
        {
            // Updating
            tbl=dc.MyCustomers.Where(selectByName).FirstOrDefault();        
            tbl.Description=strDescription;
        }
        else
        {
            // Inserting
            tbl=new MyCustomer(); 
            var maxItem=
               dc.MyCustomers.OrderByDescending(i => i.CustomerId).FirstOrDefault();
            var newID = maxItem==null ? 1 : maxItem.CustomerId+1;
            tbl.CustomerId=newID;
            tbl.CustomerName=strCustomerName; 
            tbl.Description=strDescription;
            dc.MyCustomers.AddObject(tbl);      
        }
        dc.SaveChanges(); // save all changes consistently          
        transaction.Complete(); // commit
      }
    }
    

    And the helper function to create the right transaction context is:

    // creates the right transaction scope
    public static System.Transactions.TransactionScope CreateTransactionScope() 
        // needs to add ref: System.Transactions
     { 
        var transactionOptions = new TransactionOptions 
        { 
            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted,
            Timeout = new TimeSpan(0,0,10,0,0) //assume 10 min is the timeout time
        }; 
        var scopeOption=TransactionScopeOption.RequiresNew;
        var scope = new System.Transactions.TransactionScope(scopeOption, 
                   transactionOptions); 
        return scope;
    } 
    

    The trick is here, to allow reading uncommitted - hence you can query the max ID and add 1 to id. What I wasn't able to achieve is to let SQL server generate the ID automatically, because EF doesn't allow to omit the CustomerId upon creation.

    To read more about transaction scope, look here.

提交回复
热议问题