none
What's best way of initialising property values? RRS feed

  • Question

  • I currently have an entity which has a property with an arbitrary value created in the constructor:

        public class Board
        {
            public string Code { get; private set; }
    
            Random rnd = new Random();
    
            public Board()
            {
                Code = Integer.LongRandom(0, 999, rnd)
            }
        }
    

    However, I need to check the random number hasn't been used against other Boards in the database. I don't mean the algorithm itself (simple while loop against existing values in database, etc.), rather how/where to do it in the context of EF? Is it possible/advisable to access the DbContext from within the code first entity model?

    Monday, April 9, 2012 6:51 PM

Answers

  • Hi,

    I would create a separate function that would return the next available number. In particular you could perhaps avoid querying the db each time but adding a new consumed number to this list (and initializing it once from the db). This way you could even use the same sequence for multiple entities or whatever best fit your reason for using random numbers.

    Just to be on the safe side, the other usual option would be to use an identity value or a guid in which case you don't have to check it has been already consumed (you know that but choosed random numbers ?)


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    • Marked as answer by paul1664 Tuesday, April 10, 2012 7:19 AM
    Monday, April 9, 2012 9:10 PM

All replies

  • Hi,

    I would create a separate function that would return the next available number. In particular you could perhaps avoid querying the db each time but adding a new consumed number to this list (and initializing it once from the db). This way you could even use the same sequence for multiple entities or whatever best fit your reason for using random numbers.

    Just to be on the safe side, the other usual option would be to use an identity value or a guid in which case you don't have to check it has been already consumed (you know that but choosed random numbers ?)


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    • Marked as answer by paul1664 Tuesday, April 10, 2012 7:19 AM
    Monday, April 9, 2012 9:10 PM
  • Hi Patrice,

    The original reason was to give each record (a web page) a short, unique, pseudo-random, human readable id. Guids are too long and identity values too predicable. However on reflection I think the pain of generating these outweighs the gain. I'll mark your the answer.

    Thanks, Paul.

    Tuesday, April 10, 2012 7:19 AM