I think it is a general problem in many cases, but I have not found a proper answer on the web. In my MVC application I have the following tables:
Issue Table:
---------------------------------------------
IssueID (pk) | CategoryID (fk) | IssueNumber
---------------------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3
Category Table:
-----------------------------------
CategoryID (pk) | Prefix | Name
-----------------------------------
1 | COM | Computer
2 | GEN | General
At here I use IssueID (primary key) field for both categories (COM and GEN). On the other hand, I want to generate the IssueNumber in turn (1, 2, 3 ...) without any gap for a CategoryID. On the other hand, I also want to create IssueNumber from 1 for another category as shown above. So the questions are:
1) Is there any problem regarding to the approach above? If so, what do you suggest for this?
2) How should I obtain the max value for IssueNumber before creating a record? I want to make this on the SaveChanges() method (I use Entity Framework). As I do not make IssueNumber field as PK, I cannot make the MsSQL Server auto increment this column value.
Any help would be appreciated. Thanks in advance.
Update:
Here is the solution via using lambda:
public int SaveIssue(Issue issue)
{
int max = context.Issues.Where(m => m.CategoryID == issue.CategoryID ).Max(m => m.IssueNumber);
issue.IssueNum = max + 1;
context.Issues.Add(issue);
context.SaveChanges();
return issue.IssueNum ;
}