Rob
Rob

Reputation: 361

Call method from another class DBContext

From several other classes I want to call this command to get the next id number. If there is 10 records, I want the number 11 returned.

Table1.id = NextId("table1");

public class Test
{
    private PrenDBContext db = new PrenDBContext();

    public NextId(string table)
    {
        return MaxId = db.Raknare.Where(x => x.Column.Equals(table)).Max(x => x.ID) + 1;
    }
}

If I put public static NextId I cant use db..

Upvotes: 0

Views: 565

Answers (2)

Paweł Bejger
Paweł Bejger

Reputation: 6366

You should make your PrenDBContext static as well:

public class Test 
{
        private static PrenDBContext db = new PrenDBContext();

        public static  NextId(string table)
        {
            return MaxId = db.Raknare.Where(x => x.Column.Equals(table)).Max(x => x.ID) + 1;
        } 
}

It is though more recommended to create a separate PrenDBContext each time you call a NextId method:

public class Test 
{
        public static  NextId(string table)
        {
            var db = new PrenDBContext();
            return MaxId = db.Raknare.Where(x => x.Column.Equals(table)).Max(x => x.ID) + 1;   
        } 
}

Upvotes: 1

Servy
Servy

Reputation: 203827

Create a new context every time NextId is called. Don't try to re-use the contexts between calls. Due to connection pooling (which you should ensure is enabled, if it's not) creating a new context is not particularly expensive. In fact holding onto a context when it's not needed can be far more resource intensive.

Additionally, be careful about race conditions here. If you're looking to figure out what the ID of a new item is, you should really avoid trying to solve this problem on your own. Just use a column type that allows the DB to assign its own unique value for each row. Currently you need to deal with the case where another record is created after you run this query but before you add the new record (if that is indeed what you're doing). This is very hard to manage offsite form the database itself.

Upvotes: 1

Related Questions