Should you make multiple insert calls or pass XML?

前端 未结 4 485
一整个雨季
一整个雨季 2020-12-04 02:24

I have an account creation process and basically when the user signs up, I have to make entries in mutliple tables namely User, Profile, Addresses. There will be 1 entry in

4条回答
  •  孤城傲影
    2020-12-04 02:51

    Have you noticed any performance problems, what you are trying to do is very straight forward and many applications do this day in day out. Be careful not to be drawn into any premature optimization.

    Database inserts should be very cheep, as you have suggested create a new transaction scope, open you connection, run your inserts, commit the transaction and finally dispose everything.

    using (var tran = new TransactionScope())
    using (var conn = new SqlConnection(YourConnectionString))
    using (var insetCommand1 = conn.CreateCommand())
    using (var insetCommand2 = conn.CreateCommand())
    {
        insetCommand1.CommandText = \\SQL to insert
    
        insetCommand2.CommandText = \\SQL to insert
    
        insetCommand1.ExecuteNonQuery();
    
        insetCommand2.ExecuteNonQuery();
    
        tran.Complete();
    }
    

    Bundling all your logic into a stored procedure and using XML gives you added complications, you will need to have additional logic in your database, you now have to transform your entities into an XML blob and you code has become harder to unit test.

    There are a number of things you can do to make the code easier to use. The first step would be to push your database logic into a reusable database layer and use the concept of a repository to read and write your objects from the database.

    You could of course make your life a lot easier and have a look at any of the ORM (Object-relational mapping) libraries that are available. They take away the pain of talking to the database and handle that for you.

提交回复
热议问题